Why sizeof for a Struct is Not Equal to the Sum of Each Member in C/C++



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 −

Example

#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;
}

Output

This gives the output −

8
7

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: 2020-02-11T10:37:42+05:30

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements