以一致的方式打印 (int *) 类型的指针

发布于 2024-11-06 04:25:25 字数 477 浏览 0 评论 0原文

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

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

发布评论

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

评论(2

残花月 2024-11-13 04:25:25

因为你正在做指针算术。并且指针算术始终以指针所指向的任何单位进行(在本例中为 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 to char * before doing the subtraction.

并安 2024-11-13 04:25:25

因为

((int *) &tab[1]) - ((int *) &tab[0])
=> &tab[1] - &tab[0]
=> (tab + 1) - tab
=> 1

另一方面

((intptr_t) &tab[1]) - ((intptr_t) &tab[0])
=> ((intptr_t) (tab + 1)) - ((intptr_t) tab)
=> sizeof (int)

intptr_t 是在 stdint.h 中定义的(来自 C99 标准库)。

Because

((int *) &tab[1]) - ((int *) &tab[0])
=> &tab[1] - &tab[0]
=> (tab + 1) - tab
=> 1

On the other hand

((intptr_t) &tab[1]) - ((intptr_t) &tab[0])
=> ((intptr_t) (tab + 1)) - ((intptr_t) tab)
=> sizeof (int)

where intptr_t is defined in stdint.h (from the C99 standard library).

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