【发布时间】:2021-03-24 19:46:56
【问题描述】:
This 文档中关于指向数组中单元格的指针的内容如下:
如果表达式 P 指向数组对象的第 i 个元素,则 表达式 (P)+N(等价于 N+(P))和 (P)-N(其中 N 具有 值 n) 分别指向 数组对象,前提是它们存在。
我有一个这样声明的数组:
static int heap [MANY];
我输出指向堆的指针:
printf("heap = %ld\n", heap);
输出显示如下:
heap = 4227136
那是指向heap[0] 的指针,对吧?
接下来,我输出指向heap[1]的指针:
printf("heap + 1 = %ld\n", (heap+1));
根据上面的引用,我预计指针的值1 大于4227136,即,我预计指针的值4227137。看到指针比4227136多了4,我很惊讶:
heap + 1 = 4227140
为什么指向heap[1]4的指针比指向heap[0]的指针多?
然后我尝试减去指针:我从heap[1] 中减去heap[0]:
printf("(heap+1) - heap = %d\n", ((heap+1)-heap));
我希望输出是:4227140 - 4227136 = 4
相反,我得到了1的答案:
(heap+1) - heap = 1
我很困惑。为什么我会得到这些结果?
【问题讨论】:
-
指针加减在粒度上对应类型的
sizeof。 -
I expected, based on the quote above, that the pointer would have a value 1 more than 4227136Why? 上面特别写着point to, respectively, the i+n-th and i-n-th elements of the array object。i + 1'th元素不在地址i + 1而是在i + sizeof(int)。 -
如果您想要整数数学,请使用 整数。将指针视为整数存在缺陷。指针加法/减法只是众多此类漏洞之一。做
printf("heap = %ld\n", heap);也是UB。指针不是整数不是指针。
标签: arrays c pointers pointer-arithmetic