将整数与指针相加

发布于 2024-09-01 08:20:31 字数 444 浏览 1 评论 0原文

在下面的代码中,

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雨轻弹 2024-09-08 08:20:31

dp 被定义为一个指向short 的指针,short 是两个字节。这就是编译器所关心的。要真正使 dp 成为指向 Short 的指针,您需要执行以下操作

short **dp = &p;

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;
情话已封尘 2024-09-08 08:20:31

dp 指向何处并不重要。它是指向 short 的指针,因此加法通过将内存地址增加 sizeof(short) == 2 来实现。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文