将整数与指针相加
在下面的代码中,
#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);
}
现在我得到的输出是: 0xbfb45e0a
0xbfb45e0c
0xbfb45e04
0xbfb45e06
这里我理解了p和p+1,但是当我们做dp+1时,那么由于dp指向short的指针, 由于指向 Short 的指针大小为 4 个字节,因此 dp+1 应增加 4 个单位,但它
仅增加 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
dp
被定义为一个指向short 的指针,short 是两个字节。这就是编译器所关心的。要真正使 dp 成为指向 Short 的指针,您需要执行以下操作dp
is defined as a pointer to a short and a short is two bytes. That's all the compiler cares about. To actually makedp
a pointer to a pointer to a short, you need to dodp
指向何处并不重要。它是指向short
的指针,因此加法通过将内存地址增加sizeof(short) == 2
来实现。It doesn't matter where
dp
points. It is pointer toshort
so addition works by increasing memory address bysizeof(short) == 2
.