Pointers to Arrays in C


In c programming language, when we declare an array the compiler allocates required amount of memory and also creates constant pointer with array name and stores the base address of that pointer in it. The address of first element of an array is called as base address of that array.

The array name itself acts as pointer to the first element of that array. Consider the following example of array declaration...

int  marks[6] ;

For the above declaration, the compiler allocates 12 bytes of memory and the address of first memory location (i.e., marks[0]) is stored in a constant pointer called marks. That means in the above example, marks is a pointer to marks[0].

Example Program

#include<stdio.h>
#include<conio.h>

void main()
{
   int marks[6] = {89, 45, 58, 72, 90, 93} ;
   int *ptr ;
   
   clrscr() ;

   ptr = marks ;
   printf(“Base Address of 'marks' array = %u\n”, ptr) ;
   
   getch() ;
}

Points to be Remembered

  1. An array name is a constant pointer.
  2. We can use the array name to access the address and value of all the elements of that array.
  3. Since array name is a constant pointer we can't modify its value.

Consider the following example statements...

ptr = marks + 2 ;

Here, the pointer variable "ptr" is assigned with address of "marks[2]" element.

printf("Address of 'marks[4]' = %u", marks+4) ;

The above printf statement displays the address of element "marks[4]".

printf("Value of 'marks[0]' = %d", *marks) ;
printf("Value of 'marks[3]' = %d", *(marks+3)) ;

In the above two statements, first printf statement prints the value 89 (i.e., value of marks[0]) and the second printf statement prints the value 72 (i.e., value of marks[3]).

marks++ ;

The above statement generates compilation error because the array name acts as a constant pointer. So we can't change its value.

In the above example program, the array name marks can be used as follows...

marks is same as &marks[0]
marks + 1 is same as &marks[1]
marks + 2 is same as &marks[2]
marks + 3 is same as &marks[3]
marks + 4 is same as &marks[4]
marks + 5 is same as &marks[5]
*marks is same as marks[0]
*(marks + 1) is same as marks[1]
*(marks + 2) is same as marks[2]
*(marks + 3) is same as marks[3]
*(marks + 4) is same as marks[4]
*(marks + 5) is same as marks[5]

Pointers to Multi Dimensional Array

In case of multi dimensional array also the array name acts as a constant pointer to the base address of that array. For example, we declare an array as follows...

int  marks[3][3] ;

In the above example declaration, the array name marks acts as constant pointer to the base address (address of marks[0][0]) of that array.
In the above example of two dimensional array, the element marks[1][2] is accessed as *(*(marks + 1) + 2).