C Pointers and Arrays

In this article, you'll learn to manipulate arrays using pointers with the examples.

Before you learn about how pointers can be used to work with arrays, be sure to check these two topics:

Now, check this simple program. This program prints address of each individual element of an array.

#include <stdio.h>
int main()
{
   int x[4];
   int i;

   for(i = 0; i < 4; ++i)
   {
      printf("&x[%d] = %u\n", i, &x[i]);
   }

   printf("Address of array x: %u", x);

   return 0;
}

When you run the program, the output will be something like:

&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Address of array x: 1450734448

There is a difference of 4 bytes between two consecutive elements of array x. It is because the size of int is 4 bytes (on our compiler).

Notice that, printing &x[0] and x gave us the same result.


Relation between Arrays and Pointers

Consider an array:

int x[4];

Relation between arrays and pointers

From the above example, it's clear that x and &x[0] both contains the same address. Hence, &x[0] is equivalent to x.

And, x[0] is equivalent to *x.

Similarly,

  • &x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1).
  • &x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).
  • ...
  • Basically, &x[i] is equivalent to x+i and x[i] is equivalent to *(x+i).

Example 1: Pointers and Arrays

#include <stdio.h>
int main()
{
  int i, x[6], sum = 0;
  printf("Enter 6 numbers: ");
  for(i = 0; i < 6; ++i)
  {
      scanf("%d", x+i);

      sum += *(x+i);
  }
  printf("Sum = %d", sum);
  return 0;
}

When you run the program, the output will be:

Enter 6 numbers:  2
 3
 4
 4
 12
 4
Sum = 29 

In most contexts, array names "decays" to pointers. In simple words, array names are converted to pointers. That's the reason why you can use pointer with the same name as array to manipulate elements of the array. However, you should remember that pointers and arrays are not same.

There are few cases where array name doesn't decay into a pointer. To learn more, visit: When does array name doesn't decay into a pointer?


Example 2: Arrays and Pointers

#include <stdio.h>
int main()
{
  int x[5] = {1, 2, 3, 4, 5};
  int* ptr;

  ptr = &x[2]; 

  printf("*ptr = %d \n", *ptr);
  printf("*ptr+1 = %d \n", *ptr+1);
  printf("*ptr-1 = %d", *ptr-1);

  return 0;
}

When you run the program, the output will be:

*ptr = 3 
*ptr+1 = 4 
*ptr-1 = 2

In this example, &x[2] (address of the third element of array x) is assigned to the pointer ptr. Hence, 3 was displayed when we printed *ptr.

And, printing *ptr+1 gives us the fourth element. Similarly, printing *ptr-1 gives us the second element.