0

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?

Community
  • 1
  • 1
injoy
  • 3,993
  • 10
  • 40
  • 69

2 Answers2

4

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.

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. 
Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
1
because of Packing and byte alignment<br/>

The general answer is that compilers are free to add padding between members for alignment purpose. or we can say that, You might have a compiler that aligns everything to 8 bytes.

Ravindra Bagale
  • 17,226
  • 9
  • 43
  • 70