You are here:

C/double pointer behaviour

Advertisement


Question
Hi Zlatko

   Please find the following code snippet.
  int arr[3][4] = {10,20,30,40,50,60,70,80,90,100,110,120};
  int i;
  int **pptr = arr;
  for(i=0;i<12;i++)
     printf("%d  ",*pptr++);

o/P:10 20 30 40 50 60 70 80 90 100 110 120

  pptr is a double pointer storing address of double dimensional array. then how printf("%d  ",*pptr++); is able to print all the values.

Thanks
Bhupal.

Answer
Hello Bhupal

That is a good question. The code happens to work for integers, but if you change it to shorts, you will find that it will not work. For example, this code will print incorrect results.

int main()
{
   short arr[3][4] = {10,20,30,40,50,60,70,80,90,100,110,120};
   int i;
   short **pptr = arr;
   for(i=0;i<12;i++)
       printf("%hd  ",*pptr++);
}

When you have int **p you are saying that p is a pointer, and what it points to (the target) is also a pointer. The compiler then treats the contents of arr as pointers when the contents are accessed through pptr.

Pointers and integers are the same size on 32 bit machines, so the integer values in arr take up the same space as they would if they were pointers. The program prints the contents of the array with printf *pptr and it does not matter if the contents are integers or pointers because both types are just 4 byte numbers.

The contents of arr are still accessed with the single de-reference (*pptr). Your program never actually does a double de-reference (**pptr) so your program never actually uses the values in arr as pointers.

The correct code would be:
int *pptr = arr;

I hope that answers your question.
Best regards
Zlatko

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.