C: Pointers and Arrays

In C, the array name itself is a pointer to the first element of the array. Consider an integer array a below consisting of three elements 1, 2, and 3. Therefore, the name a here contains the address of the first element 1. And hence, printing a and &a[0] yields the same address


int a[3] = {1,2,3};
printf("%p", a);
printf("%p", &a[0]);

Pointers and Integer Arrays

We declare an integer pointer p


int a[3] = {1,2,3};
int *p;
p = &a[0];

which points to a[0], the first element of the array a, and contains its address. Equivalently, the last statement can also be written just as


p = a;

and p gives the address of a[0]. In the program below, *p gives the value of a[0]


int a[3] = {1,2,3};
int *p;
p = &a[0];
printf("%d", *p);

The address of the second element in the array a is given by p+1 (and hence equal to &a[1]), and that of the third element is given by p+2 and their respective values can be accessed using the usual * operator as *(p+1) and *(p+2).

Pointers and Char Arrays

We have seen that in C, strings are represented as arrays of characters, each terminated by the escape sequence '\0', known as the null character. An example is shown below


char str[] = "eadem mutata resurgo";

str is a character array, holding a sequence of characters including the null character \0 at the end. Alternatively, we can create strings using pointer variables of type char as shown below


char *ptr = "eadem mutata resurgo";

ptr is a character pointer which is initialized to point to the first character of the string literal "eadem mutata resurgo." But contrast to the character array, we cannot modify the string to which the character pointer ptr points simply by assigning some character to it, as done below


ptr[0] = 'E';