Easy Tutorial
❮ C Examples Swapping C Exercise Example19 ❯

Pointer to an Array in C

C Arrays

You can skip this chapter initially and come back to it after understanding the concept of C pointers.

If you are familiar with the concept of pointers in C, you can start this chapter. The name of an array is a constant pointer to the first element of the array. Therefore, in the following declaration:

double balance[50];

balance is a pointer to &balance[0], which is the address of the first element of the balance array. Thus, the following snippet assigns the address of the first element of balance to p:

double *p;
double balance[10];

p = balance;

Using the array name as a constant pointer is legal, and vice versa. Therefore, *(balance + 4) is a legal way to access the data in balance[4].

Once you store the address of the first element in p, you can access the array elements using *p, *(p+1), *(p+2), etc. The following example demonstrates these concepts:

Example

#include <stdio.h>

int main ()
{
   /* An array with 5 elements */
   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
   double *p;
   int i;

   p = balance;

   /* Output the value of each element in the array */
   printf( "Array values using pointer\n");
   for ( i = 0; i < 5; i++ )
   {
       printf("*(p + %d) : %f\n",  i, *(p + i) );
   }

   printf( "Array values using balance as address\n");
   for ( i = 0; i < 5; i++ )
   {
       printf("*(balance + %d) : %f\n",  i, *(balance + i) );
   }

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Array values using pointer
*(p + 0) : 1000.000000
*(p + 1) : 2.000000
*(p + 2) : 3.400000
*(p + 3) : 17.000000
*(p + 4) : 50.000000
Array values using balance as address
*(balance + 0) : 1000.000000
*(balance + 1) : 2.000000
*(balance + 2) : 3.400000
*(balance + 3) : 17.000000
*(balance + 4) : 50.000000

In the above example, p is a pointer to a double, which means it can store the address of a double type variable. Once we have the address in p, *p will give the value stored at the corresponding address in p, as demonstrated in the example above.

C Arrays

❮ C Examples Swapping C Exercise Example19 ❯