Why is not sizeof for a struct equal to the sum of sizeof of each member in C/C++?

C++Server Side ProgrammingProgramming

The difference between sizeof for a struct and the sum of sizeof of each member of that struct is due to byte padding and alignment. Every data type in C/C++ has a alignment requirement. A processor will have processing word length of its architecture. On a 32 bit machine, the processing word size will be 4 bytes or 32 bits. For example, If you have the struct −


#include <iostream>
using namespace std;
struct X
   char b[3];
   int c;
int main()
   char b[3];
   int c;
   int total = sizeof(b) + sizeof(c);
   cout << sizeof(X) << endl;
   cout << total;


This gives the output −


On my 64 bit machine. Why is this? Its because in the struct, it takes the char array and puts it in memory but now if it puts the int whose size is 4 bytes next to it, the rules of alignment are voilated. So the extra byte at end of b is skipped and c starts from the 4 byte boundry. This causes the extra size.

You can read more about these rules at https://en.wikipedia.org/wiki/Data_structure_alignment.

Updated on 11-Feb-2020 10:37:42