C Programming

Pointers and Arrays

Posted on 21st October 2014

In C, an array name variable is actually a pointer to the first element of the array. This gives us the ability to manipulate array elements using pointer arithmetic.

Consider an array that contains five elements of type integer that is declared and initialized as below:

int arr[5] = {5, 10, 15, 20, 25};

One way of accessing the array elements is by specifying the array index inside square brackets []. Thus arr[0] is the first element, arr[1] is the second element and so on.

An alternate way of accessing the first element of the array is by writing *arr since the array variable name arr is a pointer to the first element of the array.

To access the second element of the array we just need increment the pointer arr by 1, that is *(arr+1). The (n+1)th element can be accessed by *(arr+n).

Pointer Arithmetic

You could assign the address of an array element to a pointer variable. For example to assign the first array element

ptr = arr;

or

ptr = &arr[0];

To assign the 3rd element

ptr = &arr[2];

You could increment or decrement the pointer variable

ptr++;

or

ptr--;

You could add or subrtact a constant integer the pointer variable

r = *(ptr+5);

or

r = *(ptr-3);

The parenthesis in the above statements are important as the pointer dereferencing operator * has higher priority than + and - operators.

*(ptr+5) is NOT the same as *ptr+5. The first statement adds 5 to the pointer and the second statement adds 5 to the content pointed by the pointer variable.

The following example demonstrates how to navigate through the array using pointers although the commonly used method is to used array indices.

#include <stdio.h>

main()
{
 int arr[5] = { 5, 10, 15, 20, 25 };
 int *ptr;
 
 ptr = arr;

 for (int i = 1; i <= 5; i++) {
 	printf("Array element %d is %d\n", i, *ptr++);
 }

return 0;

}

Post a comment

Comments

Nothing yet..be the first to share wisdom.