我最近看到的代码示例:
#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/