以一致的方式打印 (int *) 类型的指针
我在 C: 中有这段代码,
int tab[10] = {3, 10, 5, 7, 9, 4, 9, 4, 6, 8, 0};
printf("(int*)&tab[0]=%p (int*)&tab[1]=%p (int*)&tab[1]-(int*)&tab[0]=%d\n", (int*)&tab[0], (int*)&tab[1], ((int*)&tab[1]) - ((int*)&tab[0]));
它返回:
(int*)&tab[0]=0xbf9775c0 (int*)&tab[1]=0xbf9775c4 (int*)&tab[1]-(int*)&tab[0]=1
我不明白的是为什么最后返回的差异是 1 而不是 4。谁能告诉我一种以连贯的方式打印它们(地址及其差异)的方法(int *)?
I have this code in C:
int tab[10] = {3, 10, 5, 7, 9, 4, 9, 4, 6, 8, 0};
printf("(int*)&tab[0]=%p (int*)&tab[1]=%p (int*)&tab[1]-(int*)&tab[0]=%d\n", (int*)&tab[0], (int*)&tab[1], ((int*)&tab[1]) - ((int*)&tab[0]));
And it returns:
(int*)&tab[0]=0xbf9775c0 (int*)&tab[1]=0xbf9775c4 (int*)&tab[1]-(int*)&tab[0]=1
What I do not understand is that why the difference returned is 1 instead of 4 at the end. Could anyone tell me a way to print them (addresses and their difference) in a coherent way for (int *)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为你正在做指针算术。并且指针算术始终以指针所指向的任何单位进行(在本例中为 4,因为在您的系统上
sizeof(int) == 4
)。如果您想知道原始地址的差异,则可以将减法结果乘以
sizeof(int)
,或者在进行减法之前将指针强制转换为char *
。Because you're doing pointer arithmetic. And pointer arithmetic is always done in units of whatever the pointer is pointing to (which in this case is 4, because
sizeof(int) == 4
on your system).If you want to know the difference in raw addresses, then either multiply the result of the subtraction by
sizeof(int)
, or cast the pointers tochar *
before doing the subtraction.因为
另一方面
intptr_t 是在 stdint.h 中定义的(来自 C99 标准库)。
Because
On the other hand
where intptr_t is defined in stdint.h (from the C99 standard library).