【发布时间】:2020-05-18 09:47:54
【问题描述】:
我在确定结构的大小时遇到了一个问题。我发现可以在 sizeof 操作中使用前面的关键字 struct 来确定结构的大小,尽管没有为相应的结构创建对象:
例子:
#include <stdio.h>
int main()
{
struct struct1
{
char a[20];
int v,i;
double grw;
};
printf("Size of struct1 in Byte: %lu",sizeof(struct struct1));
return 0;
}
输出:
Size of struct1 in Byte: 40
这怎么可能?
如果尚未创建此结构的对象,sizeof 如何借助 sizeof 操作内的 struct 关键字确定结构的大小?
或者已经创建了一个struct1 对象,我不知道?
我认为结构只是一种数据类型,而不是它自己类型的对象。
【问题讨论】:
-
如果编译器不知道它的大小,它如何分配
struct struct1类型的对象? (struct关键字不相关。sizeof(int)也很好。) -
这个 sizeof 只是告诉你创建一个 struct1 类型的“对象”需要多少内存
-
sizeof从其结构中推断出struct的大小。
标签: c memory data-structures struct sizeof