All about Arrays

Shreya
3 min readJul 2, 2020

Part 1

Arrays is a collection of elements of same type grouped under one name.

int x=10; (Here, x is a scalar variable where you can store only one element.)

int A[5]; (Here, A is a vector variable called Array.)

Declaration and Initialization

  1. int A[5]; Array of Size 5 is declared and it contains garbage values.
  2. int A[5]={2,4,6,8,10}; Initialized and declared
  3. int A[5]={2,4}; First and second index contain 2 and 4 whereas the rest are initialized to zero.
  4. int A[5]={0}; All the 5 elements are initialized to zero.
  5. int A[ ]={2,4,6,8,9}; Initialized and declared without specifying the size.

Traversing an Array (Using for loop)

for(i=0;i<5;i++) { printf(“%d”, A[i]); }

Printing an array

All three given below are equivalent and they print the second index element.

printf(“%d”, A[2]); Subscript

printf(“%d”, 2[A]);

printf(“%d”, *(A+2)); Pointer Arithmetic

Print Address of Array

Static vs Dynamic Array

Static Array means that the size of memory/array will be decided at compile time. Memory will be allocated only at running time. Whereas ,a dynamic array is an array with a big improvement: automatic resizing. One limitation of arrays is that they’re fixed size, meaning you need to specify the number of elements your array will hold ahead of time. A dynamic array expands as you add more elements.

Note: Size of an array can be decided at runtime in C++, but in C language it has to be mentioned at compile time ONLY. And both arrays are created in Stack as part of activation record of main function.

In C++

In the image given above, Both arrays A and B are created in Stack whereas the size of array B is declared at run time.

Now we will see how to store an Array in Heap Memory.

Note: For accessing anything from heap, we must have a pointer.

Dynamic Array Declaration

A pointer p is used to access the array A of size 5 (for now)

In any language, when you declare a variable, the memory for that variable will go inside the stack.

Heap memory cannot be accessed directly. We need memory in heap, then we need to use the malloc function in C or new function in C++.

Heap memory allocation

If unused memory is not released then memory leak problem may occur.

Memory Release

Increasing Array Size

Let’s say you have an array of size 5 in your memory but you don’t know whether the next memory block is free or not. Therefore, you can’t increase array size directly. You have to take a bigger array instead, copy small array’s elements and then delete small array.

Here, given that size 5 of space was insufficient we made a bigger array and shifted the elements of the previous array into the bigger array of size 10.

That’s all for today. I’ll be back with part 2 where we’ll be discussing all about 2-d and 3-d Arrays.

Ciao!

--

--