结构对字体大小的贡献
我想知道为什么以下两种类型
struct {
double re[2];
};
在C中具有
double re[2];
相同的大小? struct 不会增加一点大小开销吗?
I am wondering why the following two types
struct {
double re[2];
};
and
double re[2];
have the same size in C? Doesn't struct add a bit of size overhead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
不,它只是将所有元素组合成一个更高级别的元素,其大小只是各个元素大小的总和(加上一些取决于对齐规则的填充,但这超出了这个问题的范围)。
No, it just merely composes all the elements into one higher-level element whose size is merely the individual elements' sizes added up (plus some padding depending on alignment rules, but that's out of the scope of this question).
如果有帮助的话就不会——不。 C 像瘟疫一样避免开销。 具体来说,它避免了这种情况下的开销。
如果您使用不同的结构,您可能会看到差异:
如果您的机器要求
double
在 8 字节边界上对齐(并且sizeof(double) == 8
,这是正常的,但标准没有强制要求),那么你会发现该结构体占用了16个字节。Not if it can help it - no. C avoids overhead like the plague. And specifically, it avoids overhead in this context.
If you used a different structure, you might see a difference:
If your machine requires
double
to be aligned on an 8-byte boundary (andsizeof(double) == 8
, which is normal but not mandated by the standard), then you will find that the structure occupies 16 bytes.不,该结构不必添加任何内容。 与 Java 或 .NET 中的类(和结构)具有许多其他职责不同,在 C 和 C++ 中,它们只是用于保存许多数据成员的容器。 在 C++ 中,它们可能必须存储 vtable 来解析虚拟函数调用(如果存在),但一般来说,不需要,结构本身没有开销。
一个例外是:
空结构的大小不会为零。 结构必须具有一些非零大小,因为每个对象都必须有唯一的地址。 (否则你将无法创建这些结构的数组)
Nope, the struct doesn't have to add anything. Unlike in Java or .NET, where classes (and structs) have a bunch of other responsibilities, in C and C++, they are simply containers used to hold a number of data members. In C++, they may have to store a vtable to resolve virtual function calls if any exist, but in general, no, a struct itself has no overhead.
The one exception is this:
The size of an empty struct will not be zero. A struct has to have some nonzero size since every object has to have a unique address. (Otherwise you wouldn't be able to create an array of these structs)
不会。Struct 不会增加任何大小,也不会在编译后的 C 中产生任何开销。
它是一层语法,需要编译器进行额外的工作,但在运行时没有开销。
C 是一种极其“赤裸”的语言,这意味着除非需要,否则什么都没有。
所以问问自己,“结构需要什么开销?”,你不会找到任何开销。
No. Struct does not add any size, or have any overhead in the compiled C.
It is a layer of syntax that requires additional work by the compiler, but has no overhead at runtime.
C is an extremely "naked" language, meaning that nothing is there unless required.
So ask yourself, "What overhead does a struct REQUIRE?", and you won't find any.
不,没有。
这是结构的优点之一(为什么它们在老式 TCP/IP 编程中如此有用)。
这是表示内存/缓冲区布局的好方法。
No it doesnt.
That's one of the good points of structs (why they were so helpful in old school TCP/IP programming).
It's a good way to represent the memory/buffer layout.
没有C中的结构类型,只是在内存中按顺序布局成员
no the struct type in C just sequentially layout the members in memory
有时,请参阅:http://en.wikipedia.org/wiki/Sizeof
sometmes, see: http://en.wikipedia.org/wiki/Sizeof