Course Content
Programming in C
About Lesson

There is a strong relationship between arrays and pointers. Any operation that can be achieved by array subscripting can also be done with pointers, with the pointer version being faster but usually harder to understand.

int arr[5];

defines an array arr of size 5, i.e. a block of 5 consecutive int objects named a[0], a[1], a[2], a[3] and a[4].
The notation a[i] refers to the i-th element of the array. Let’s declare a pointer ptr to an int:

int *ptr;

then

ptr = &arr[0];

sets ptr to point to the zeroth element of array arr (ptr contains the address of arr[0]).


Now the following statement

int x = *ptr;

will copy the contents of arr[0] into x.

If ptr points to a particular element of an array, then ptr + 1 points to the next element, ptr + i points to i elements after ptr and ptr – i points to i elements before. So, as ptr points to arr[0], *(ptr + 1) refers to the contents to arr[1]. ptr + i is the address of arr[i] and *(ptr + i) is the contents of arr[i]. These are true regardless of the type or size of the variables in the array.

ptr = &arr[0];

can also be written as

ptr = arr;

since the name of an array is synonymous to the location of the initial element.

An important difference between an array name and a pointer is that a pointer is a variable, so ptr = arr and ptr++ are legal. But an array name is not a variable, so arr = ptr and arr++ are illegal.

Scroll to Top