When a program containing an array of size n is compiled, the compiler allocates n blocks of memory for the array for storing the values of its elements. The size of each block depends on the data type of the array. For example, for the array AR [ ] defined below, five blocks of memory are allocated and each block is of the size of the memory block for an integer (i.e., 4 bytes on a 32-bit system).
int AR[5] = {12,20,8,16,40};
We know that each byte is numbered and this number represents the address of the byte. The address of an array is the address of the first element of the array. In the above array, the first element is allocated 4 bytes. The number of the first byte is the address of the element. Similarly, the second element is also residing on the next 4 bytes. Here also the number of the first byte of this block of memory is the address of the second element. The same argument holds for other elements of the array as well. The name of an array holds the address of the array. It may be extracted by simply calling the name of array as illustrated in the following code for the array AR[5]:
printf ("%p", AR) ;
The address of any element of an array may also be extracted in a similar manner. We have to call (name + offset). The offset is equal to the subscript or index value of the element. Thus, for obtaining the address of the second member of array AR [ 5] , the code may be written as given below.
printf("%p", AR +1);
Similarly, for obtaining the address of any one element of array the code may be written as follows:
printf("%p", AR +(offset of element));
The value of offset is same as the index value of the element. Program determines the address of an array and addresses of individual elements of the array.
Illustrates finding of addresses of an array and its elements
#include<stdio.h> void main() { int i; int AR[5] = {12,20,8,16, 40}; clrscr(); printf("The address of the array is: %p\n", AR); printf("The addresses of the four elements are as below.\n"); for (i =0; i<5; i++) printf("Address of AR [%d] = %p\n",i, AR+i); }
The expected output of the above program is as given below