c - 指针如何知道项目的基础大小?

标签 c pointers

如“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/

相关文章:

C++:只打印一个字符

c - 流浪\[反斜杠]在C代码中有什么意义吗?

将 8 位指针转换为 long

c++ - C++11 中的原始指针与智能指针

c - 递增指针的指针

c++ - 为什么不允许指针+指针,但允许指针+整数?

C - 将 3.00 变为 3

c - 使用 C 返回数组

c - 当用户不提供输入时,我得到 "Segmentation fault: 11"。当用户提供输入时,它可以正常工作。我怎样才能解决这个问题?

c - 为什么传递数组通用指针不起作用