The name or identifier of an array is itself a constant pointer to the array. Its value is the address of the first element of the array. Thus, a pointer to an array may be declared and assigned as shown below.
int AR[] = {10, 20, 30 ,40}; //AR is the name of array int *pAR ; // *pAR is pointer to integer pAR = AR; //Note that value of pAR is AR and not &AR.
In the above declarations, AR is the name of array and pAR is a pointer to the array. Both are, in fact, pointers to the same array AR[]. Note that pAR is assigned the value AR and not &AR because AR is itself a const pointer to the array. Its value is the address of the first element of the array. Now, pAR is a pointer declared for the array; pAR is also assigned the address of the first element of the array. Thus, both have same value. But the difference is that a pointer to an array such as pAR may be incremented or decremented in order to move from one element of the array to another element of the array, while the name of an array is a constant pointer to the array and cannot be incremented or decremented. If a pointer to an array such as pAR is incremented by 1 it would point to the next element of the array, i.e., the value of the pointer (pAR) would increase by the number of bytes allocated to one array element. This is how pointer arithmetic is different from arithmetic operations performed on ordinary variables. Since address of the array is also the address of the first element of the array, the assignment of pAR may also be written as below.
int *pAR = &AR[0];
The values of elements of the array AR [4] may be obtained from its pointer pAR in the following manner:
* pAR = 10 *(pAR+l) = 20 *(pAR+2) = 30 *(pAR+3) = 40
The index values of the array elements are 0, 1, 2, and 3 that are respectively equal to the offset values used with pointer pAR in the above code. Since AR is also a pointer to the array, the values of array elements may also be obtained by dereferencing the pointers AR, AR+ 1, AR+ 2, and AR+ 3 as given below.
* AR = 10 *(AR+l) = 20 *(AR+2) = 30 *(AR+3) = 40
The difference between AR and the declared pointer pAR is that we can increment pAR to access the next element of array, i.e., ++pAR or pAR++ is valid. But AR cannot be incremented, i.e., ++AR or AR++is invalid. However, we may use an offset as shown above for the same purpose. This is also illustrated in Program.
#include<stdio.h> int main () { int i; int AR [] = { 10, 20, 30, 40, 50 }; int *pAR = AR; clrscr(); printf("\nAR = %p\t &AR[0] = %p\t pAR = %p\n",AR,&AR[0],pAR); for (i=0;i<5;i++) printf("*pAR = %d\t AR[%d] = %d\n",*pAR++, i, AR[i]); return 0; }
The expected output of the above program is as given below.