c - 空指针操作

标签 c pointers void

已知void pointer airthmetic是无效的。

int main {
    int b = 10;
    void *a = (void *) &b;
    void *c = a + 1;
    printf ("%p\n", a);
    printf ("%p\n", c);
}

    Output:
     0x7fff32941d1c             
     0x7fff32941d1d

我读到上面的 airthmetic 是意外行为,我们不能依赖它。

现在进入实际问题。我正在获取一个空指针数组。

int main()
{
    void *a[10];
    void **b = a;
    void **c = (a + 1);
    printf ("%p\n", b);
    printf ("%p\n", c);
}

Output:
0x7fff8824e050          
0x7fff8824e058

您能否解释一下上面的行为,其中使用了双指针(指向 void 指针的指针)。这是预期的行为吗?

最佳答案

Can you please explain the above behavior, where a double pointer (pointer to a void pointer is used). Is it expected behavior?

是的,这是预期的行为。

那是因为指针指向的对象的大小是已知的。它是 sizeof(void*)

如果指针的值用纯整数值表示,

(a + 1) == a + 1*sizeof(void*)

在您的平台上,sizeof(void*) 似乎是 8

关于c - 空指针操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30045174/

相关文章:

c - PC Lint 错误 714

c - 在C中,Print语句没有在for循环中打印

c - 段错误和地址清理器

c - 何时在 char 指针上使用 void 指针?

c - 这个 C 代码是什么意思 (G_GNUC_PRINTF)?

c - 将 C 程序分成 void 函数

c - 我的段错误发生在哪里? C

无法理解 C 中指针的内存地址结果

C: Segmentation Fault -- 堆栈实现链表

c - 'pre' - 分配指针但尚未使用是什么意思?