为什么不同结构的大小的输出相同

Why the outputs of the size of the different structures are the same?

本文关键字:输出 为什么不 结构      更新时间:2023-10-16

可能的重复:
结构填充

该程序如下:

#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字节保持一致。