为什么不同结构的大小的输出相同
Why the outputs of the size of the different structures are the same?
可能的重复:
结构填充
该程序如下:
#include <iostream>
using namespace std;
struct node1 {
int id;
char name[4];
};
struct node2 {
int id;
char name[3];
};
int
main(int argc, char* argv[])
{
cout << sizeof(struct node1) << endl;
cout << sizeof(struct node2) << endl;
return 0;
}
,编译器是g++ (GCC) 4.6.3
。输出为:
8
8
我真的不明白为什么这样。为什么sizeof(struct node2)
的输出不是7?
这是因为结构在边界处对齐。通常为4个字节(尽管可以更改) - 这意味着结构中的每个元素至少为4个字节,如果任何元素的大小小于4个字节,则在末尾将填充物添加到它们。
因此,这两个都是8个字节。
size of int = 4
size of char = 1
size of char array of 3 elements = 3
total size = 7, padding added (because of boundary) = +1 byte
for second structure:
sizeof int = 4
sizeof char = 1
sizeof char array of 4 elements = 4
total size = 8. no padding required.
because of Packing and byte alignment<br/>
一般的答案是,为了对齐目的,编译器可以自由添加成员之间的填充。或者我们可以说,您可能有一个编译器将所有内容都与8字节保持一致。
相关文章:
- 为什么不;名字在地图上是按顺序排列的吗
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 为什么不递增?(构造函数)
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 为什么不允许使用可变长度数组作为向量元素?
- C++:为什么不调用移动构造函数?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 为什么不能用常量表达式声明数组?
- 显示C++输出而不返回值
- 为什么不能直接引用作用域枚举类成员,而不能为无作用域枚举生成类成员?
- C++ queue.front();为什么不从第一个元素开始呢?
- 为什么不允许这种交叉广播?
- 执行此代码时,它不显示任何输出.为什么?
- 通过构造函数方法输出的类到类类型转换是 5500 为什么不是 5555
- 为什么我的数组输出一个不在其中的元素
- 为什么无论情况如何,程序输出都不真实?
- 默认情况下构造函数插入数据后,我没有得到任何输出,但我不确定为什么不
- 如果语句不求值为false?程序给出奇怪的输出.为什么