array_thumbnail

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[3];  //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 :

Array

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[0].
The compiler interprets a[0] as *(a + 0) =*(0 + a) = *a.
Similarly, the 2nd element of the array, a[1] 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[1] => *(a + 4 bytes) (considering, compiler takes 4 bytes to store an integer) of a[0].
a[2] = *(a + 4 bytes) as, (for a[0]) + 4 bytes (for a[1]).

Example
#include <stdio.h>

int main() {
	int a[3]={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[0] = %d and &a[0] =%p\n",a[0],&a[0]);
	printf("a[1] = %d and &a[1] =%p (&a[1]=base address + 4 bytes)\n",a[1],&a[1]);
	printf("a[2] = %d and &a[2] =%p (&a[2]=base address + 4*2=8 bytes)\n",a[2],&a[2]);
	printf("a[0] = *(a+0)=%d\n",*a);
	printf("a[1] = *(a+1)=%d\n",*(a+1));
	printf("a[2] = *(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[0] = 2 and &a[0]=0x7ffd759a5080
a[1] = 1 and &a[1]=0x7ffd759a5084 (&a[1]=base address + 4 bytes)
a[2] = 4 and &a[2]=0x7ffd759a5088 (&a[2]=base address + 4*2=8 bytes)
a[0] = *(a+0)=2
a[1] = *(a+1)=1
a[2] = *(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:

array in memory

Fig. 2: Memory representation of array shown above

For 2-Dimensional arrays click here.

What do you think about the article?