Adding an integer to a pointer

In the 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 I got the result: 0xbfb45e0a
0xbfb45e0c
0xbfb45e04
0xbfb45e06

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

+2
pointers integer addition


a source to share


2 answers


dp

is defined as a pointer to short, and short is two bytes. This applies to the entire compiler. To actually make a dp

pointer to pointer short, you need to do



short **dp = &p;

      

+5


a source to share


It doesn't matter where it dp

points. It is a pointer to short

, so the addition works by increasing the memory address by sizeof(short) == 2

.



+3


a source to share







All Articles