views:

30

answers:

2

In following code,

#include<stdio.h>   
int main()  
{  
  short a[2]={5,10};  
  short *p=&a[1];  
  short *dp=&p;  
  printf("%p\n",p);  
  printf("%p\n",p+1);  
  printf("%p\n",dp);  
  printf("%p\n",dp+1);  
}  

Now the output I got was : 0xbfb45e0a
0xbfb45e0c
0xbfb45e04
0xbfb45e06

Here I understood p and p+1, but when we do dp+1, then since dp points to pointer to short, and since pointer to short is 4 bytes in size, so dp+1 should increase by 4 units but it
is increasing only by 2.
Please explain reason.

+5  A: 

dp is defined as a pointer to a short and a short is two bytes. That's all the compiler cares about. To actually make dp a pointer to a pointer to a short, you need to do

short **dp = &p;
Toon Van Acker
+3  A: 

It doesn't matter where dp points. It is pointer to short so addition works by increasing memory address by sizeof(short) == 2.

pajton