c - sizeof() 如何处理取消引用?

标签 c pointers malloc sizeof

我最近看到的代码示例:

#include <stdio.h>
#include <stdlib.h>

struct x {
       int a;
       int b;
};

int main(void) {

    struct x *ptr = malloc(sizeof(*ptr));
    return 0;
}
  • sizeof(*ptr) 是如何工作的?

  • 如何取消引用未定义的指针并将其提供给 sizeof() 并产生正确的大小? (当然它应该导致未定义的行为,因为它是未定义的)

  • 最后,C 标准是否定义了这种行为? (也许表明它在 C 中是合法的,我找不到任何东西)

最佳答案

ptr 实际上并没有在这里取消引用。 sizeof 运算符的操作数,在本例中为表达式 *ptr,仅查看其类型。

这在 C standard 的第 6.5.3.4p2 节中有详细说明关于 sizeof 运算符:

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant

在这种特殊情况下,*ptr 未被评估,但它被视为具有类型 struct x,因此 sizeof(*ptr)计算为一个常量,它是 struct x 的字节大小。

关于c - sizeof() 如何处理取消引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73653971/

相关文章:

当您不想传递任何变量时,您可以在 C 中使用变长参数函数吗?

带有数组和指针的 C 字符串函数(strcpy、strcat...、strstr)

c - 为什么我得到 "assignment makes pointer from integer without a cast"?

将结构复制到动态分配的结构数组中

c - gsl 复数矩阵 * 复数 vector

c - 为什么当输入的找零是 2.2 时,输出显示所需的最小硬币数的正确答案,但当我输入 4.2 时却显示错误的输出?

c - 指向数组的指针,分配数组

c - 错误./thrash : free(): invalid pointer

c++ - realloc() 的性能消耗

c++ - 能不调用构造函数就调用析构函数吗?