2012-10-19 147 views
0

可能重复:
Struct Padding为什么不同结构大小的输出是相同的?

该方案如下:

#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?

+2

'node2' has padding – Musa

回答

4

这是因为结构在边界对齐。通常为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. 
1
because of Packing and byte alignment<br/> 

一般的答案是,编译器可以自由成员之间添加填充物对位的目的。或者我们可以这样说,你可能有一个编译器将所有内容对齐到8个字节。

相关问题