Introduction to passing pointer to array in C

If you don’t have any idea about pointer then read about pointer in C before learning pointer to array in C. That will help you to understand this article.

Pointer can point the 0th element of an array as well as the whole array. Actually pointer can be very useful if you work with multidimensional arrays. Let’s have a look at the program bellow.

// pointer to array in c
#include<stdio.h>
int main(){
  int myArray[5] = {2, 4, 6, 8, 10};
  int *ptr = myArray;     // points to the first element of array

  printf("Address of %d is = %p\n", *ptr, ptr);
  return 0;
}

Output of this pointer to array program

pointer to array in c, pointer and array in c

Here pointer ptr points to the first element of the array which contains the value 2. Obviously we can also points to the whole array by a pointer. See the example program bellow where the pointer points to the address of the array.

// pointer points to the whole array in c
#include <stdio.h>
int main(){
    int *p;

    int (*ptr)[5];
    int arr[5];

    p = arr;    // points to the first element of array

    ptr = &arr;    // points to whole array

    printf("p = %p and ptr is = %p\n", p, ptr);

    p++;
    ptr++;

    printf("p = %p and ptr is = %p\n", p, ptr);

    return 0;
}

See the output:

use pointer to array in c, pointer and array

Here pointer p points the zeroth element of the array arr and ptr points to the whole array arr. Although base type of p is integer, the base type of ptr is an array of 5 integers.

When we write ptr++, then ptr will be shifted forward by 20 bytes as pointer arithmetic is performed relative to the base size.

Example C program using pointer to array

You will clear from the following example C program in which we have used pointer and array. Let’s try to understand the program.

// pointer to array program in C
#include <stdio.h>
int main (){
   double weight[5] = {65.50, 82.00, 73.40, 79.50, 58.70};
   double *ptr;
   int c;

   ptr = weight;

   printf( "Array elements using pointer is as follows : \n");

   for ( c = 0; c < 5; c++ ){
      printf("*(ptr + %d) : %.3f\n",  c, *(ptr + c) );
   }

   printf( "\nArray elements using address weight is as follows : \n");

   for ( c = 0; c < 5; c++ ){
      printf("*(weight + %d) : %.3f\n",  c, *(weight + c) );
   }

   return 0;
}

You will see the following output when you run this program.

pointer to array example program in c

In this example program ptr is a pointer to double which can store the address of a double type variable. When we have the address in ptr then *ptr will give us the value which is stored in that address which we have cleared from the above example here.