Possible Duplicate:
Struct Padding
The program is as below:
#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;
}
And the compiler is g++ (GCC) 4.6.3. The outputs are:
8
8
I really do not understand why is it so. Why is the output of sizeof(struct node2) not 7?
This is because structures are aligned at boundaries. Usually of 4 bytes(although it can be changed) – Which means, each element in the structure is atleast 4 bytes and if the size of any element is less than 4 bytes, then padding is added to them at the end.
hence both are 8 bytes.