如“How does pointer incrementation work?”中所问,我有一个后续问题。
指针如何知道它指向的数据的基本大小?指针是否存储基础类型的大小以便它们知道如何递增?
我希望下面的代码会将指针向前移动一个字节:
int intarr[] = { ... };
int *intptr = intarr;
intptr = intptr + 1;
printf("intarr[1] = %d\n", *intptr);
根据链接站点上已接受的答案,指针按字节递增,而不是按底层 sizeof
指向的元素递增会导致大规模的歇斯底里、困惑和困惑。
虽然我知道这可能是不可避免的结果,但我仍然不明白指针在这方面的工作原理。我不能声明一个指向某些 struct[]
类型数组的 void
指针,如果我这样做了,void
指针怎么知道增加 sizeof(struct mytype)
?
编辑:我相信我已经解决了我遇到的大部分困难,但就代码中的演示而言,我还不够。
参见此处:http://codepad.org/0d8veP4K
#include <stdio.h>
int main(int argc, char *argv[])
{
int intarr[] = { 0, 5, 10 };
int *intptr = intarr;
// get the value where the pointer points
printf("intptr(%p): %d\n", intptr, *intptr);
printf("intptr(%p): %d\n", intptr + 1, *(intptr + 1));
printf("intptr(%p): %d\n", intptr + 2, *(intptr + 2));
// the difference between the pointer value should be same as sizeof(int)
printf("intptr[0]: %p | intptr[1]: %p | difference: %d | expected: %d",
intptr, intptr + 1, (intptr + 1) - intptr, sizeof(int));
return 0;
}
最佳答案
它在类型声明中。 p1
知道类型的大小,因为它是 sizeof(*p1)
或 sizeof(int)
。 p2
不知道,因为 sizeof(void)
未定义。
int *p1;
void *p2;
p1++; // OK
p2++; // Not defined behavior in C
关于c - 指针如何知道项目的基础大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34006579/