gpt4 book ai didi

c - 在不创建对象的情况下从指针找到结构的正确大小?

转载 作者:太空狗 更新时间:2023-10-29 15:55:07 27 4
gpt4 key购买 nike

抱歉,如果标题令人困惑。这是我的结构:

struct l_list{
int number;
char *name;
double value;
struct l_list *next;
};

typedef struct l_list *PhoneBook;

主要功能:

int main(void){

printf("%u\n", sizeof(struct l_list));

PhoneBook person1;

printf("%u\n", sizeof(*person1));
printf("%u\n", sizeof(PhoneBook));

return 0;
}

输出是:

20
20
4

我知道 PhoneBook 显示 4 个字节,因为它只是指针 的大小,但是您如何找到实际结构 的大小em> 来自 typedef PhoneBook?

最佳答案

您可以使用以下内容:

printf("%zu\n", sizeof( *(PhoneBook)NULL ) );

重要的问题是为什么上述有效,你不是在 NULL pointer 上执行 indirection 这将是 undefined behavior ?不,你不是 sizeof 除了 variable length arrays根本不被评估。如果我们看一下 C99 draft standard 6.5.3.4 部分 The sizeof operator 段落 2 说(强调我的):

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.

此外,我们在第 5 段中看到以下示例,它证实了这一解读:

double *dp = alloc(sizeof *dp);

在编译时确定表达式的类型,以便计算结果。我们可以通过以下示例进一步证明这一点:

int x = 0 ;
printf("%zu\n", sizeof( x++ ));

不会增加 x

注意:%zuplatform independent sizeof 结果的格式说明符。

关于c - 在不创建对象的情况下从指针找到结构的正确大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19672769/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com