In this tutorial, we are going to learn the Array Data Structures, how to implement array in C, C++, Java, Python, How to dynamically increase the size of array.
Array is a collection of homogeneous elements stored at continuous memory locations. The name of the array is nothing but address of first memory location. Array index starts from zero(0)
Why does array index starts from zero?
Let’s consider an array ‘arr’ of size 3. Starting address of array arr is 100.
int arr[3] = {1,2,3};
// assume starting address of arr is 100
The value at arr[0] is 1 because arr[0] is nothing but *(arr+0). We can say that Array is nothing but a Pointer in C.
Starting address of array is 100 so *(arr+0) becomes *(100+0). The value at 100 is 1.
Now, arr[1] is *(arr+1) i.e. *(100+1) and here 100+1 is not equal to 101, it’s not a simple addition it’s pointer addition. Type of arr is int so it can access 4 bytes of memory at one time that’s why *(100+1) is *(104) and the value at address 104 is 2. (Size of Integer is 4 byte in gcc(C Compiler).
Advantages of arrays
- Random access of element is possible so we can access the element by position/index faster.
- Arrays have better cache locality and this is good for performance.
- Arrays represent multiple data elements of the same type using a common name i.e. name of array.
Disadvantages of arrays
Insertion and deletion costs more because elements are stored in consecutive memory locations and takes more time for shifting operation.
Concept of array is used to implement data structures like Stack, Queue, Hash Tables.
Array implementation in C and C++
int arr[3] = {1, 2, 3};
printf("%d", arr[0]); // In C Programming
cout<<arr[0]; // In C++ Programming
Array implementation in Java
int arr[]; //declaring array
arr = new int[5]; // allocating memory to array
OR
int[] arr = new int[5]; // combining above both statements in one
Array implementation in Python
# importing "array" for array operations
import array
# initializes array with signed integers(i for integer)
arr = array.array('i', [1, 2, 3])
print(arr[1])
Dynamically increase size of array in C Programming
We can increase size of array dynamically using the realloc() ( From stdlib.h header file)
The Syntax of realloc() is
realloc(pointerToArray, newSize);
#include <stdio.h>
#include <stdlib.h>
int main()
{
//a pointer to dynamically allocated memory
int *a = (int *) malloc(10 * sizeof(int)); //array of size 10
realloc(a, 10); // array of size 20
for(int i = 0; i < 20; i++)
a[i] = i + 1; //assign some values
printf("\n Elements of the array: \n");
for(int i = 0; i < 20; i++)
printf("%d\t", a[i]);
free(a); //free the dynamically allocated memory to avoid memory leaks.
return 0;
}