 # Array: memory aspect

Ankur Kulhari

An array can be defined as finite collection of homogeneous data, stored in contiguous memory locations. Where,

• finite: means the number of elements to be stored in array has to be predefined finite number.
• homogeneous: all the elements of the array should be of same type (i.e. int, char, float etc.).
• contiguous: all the elements of the array should be stored one after another in the memory. They cannot be stored in scattered manner.
###### accessing elements of an array:

To access any data, the address of memory location, where it is stored, is required. For array, the address of 1st element can be accessed through the name of the array (also called as base address of the array). Subsequent elements can be accessed with base address and the offset value of the desired element.
Let us consider following example to understand this:

```int a;  //an array which stores 3 integer (homogeneous) values stored in the
//memory in contiguous manner as shown in fig. 1
```

From the memory point of view a will look like : Fig. 1: Array in memory

If the variable a is printed, it prints the base address or the address of 1st element of the array, represented by a.
The compiler interprets a as *(a + 0) =*(0 + a) = *a.
Similarly, the 2nd element of the array, a is interpreted by the compiler as *(a + 1) = *(1 + a) => value at (base address (a) + the size of element stored before it). In this case a => *(a + 4 bytes) (considering, compiler takes 4 bytes to store an integer) of a.
a = *(a + 4 bytes) as, (for a) + 4 bytes (for a).

###### Example
```#include <stdio.h>

int main() {
int a={2,1,4};
printf("The value of variable a=%p, (base address of array)\n",a);
printf("The address of a (where a is stored) =%p\n",&a);
printf("a = %d and &a =%p\n",a,&a);
printf("a = %d and &a =%p (&a=base address + 4 bytes)\n",a,&a);
printf("a = %d and &a =%p (&a=base address + 4*2=8 bytes)\n",a,&a);
printf("a = *(a+0)=%d\n",*a);
printf("a = *(a+1)=%d\n",*(a+1));
printf("a = *(a+2)=%d",*(a+2));
return 0;
}
```
###### Output
```The value of variable a=0x7ffd759a5080, (base address of array)
The address of a (where a is stored) =0x7ffd759a5080
a = 2 and &a=0x7ffd759a5080
a = 1 and &a=0x7ffd759a5084 (&a=base address + 4 bytes)
a = 4 and &a=0x7ffd759a5088 (&a=base address + 4*2=8 bytes)
a = *(a+0)=2
a = *(a+1)=1
a = *(a+2)=4
Note: This compiler takes 4 bytes to store an integer value. & operator returns the address of variable)
```

The memory view of above example can be seen as below: Fig. 2: Memory representation of array shown above