43. Pointer to an array

The way we can have a pointer to an integer or a pointer to a float, can we also have a pointer to an array? The answer is yes. The Declaration of a pointer to an integer is int *p; but the declaration of a pointer to an array is int (*q)[4]; That means q is a pointer to an array of 4 integer. Pointer to an array, use in two dimensional arrays. When we increase a pointer to an integer it points the next element, but when we increase the pointer to an array it skip those element which you give in the bracket. In this declaration int (*q)[4]; it skip 4 element. Let us use this pointer to an array in a program. Here it is…

/*Program for pointer to an array*/

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

void main( )
{
int a[][4]= {
              5,7,5,9
              4,6,3,1
              2,9,0,6
            };
int *p;
int (*q)[4];

p=(int*)a;
q=a

printf(“\n %u %u”,p,q);
p++;
q++;
printf(“\n %u %u”,p,q);
getch();\
};

And here is the output…

65500 65500
65502 65508

To begin with both p and q contain the same address 65500. However, p is an integer pointer, whereas q is a pointer to an array of 4 integers. Hence on incrementing p it points to the next integer, whereas, q starts pointing to the next 1-D array of 4 integers. Pointer to an array is vary useful while passing a 2-D array to a function, as we would see in the next section.

Written by Arnob
Ref: “Understanding Pointers In C”

3 comments:

  1. Can you plz write an artical about arry of pointers

    ReplyDelete
  2. Thanks for your post

    ReplyDelete
  3. Asif@ thanks for your post. Yes i can.

    ReplyDelete

free counters