-1

In have this code:

#include <iostream>

using namespace std;

int main() {
    struct people {char name[50]; int tt; int gg;};
    
    struct people p1;
    cout << sizeof(p1);
    
    return 0;
}

the output is 60. Why?, I mean, the struct just would need to have 50+4+4=58 bytes. If we change the name[50] to name[20], we have the output: 28 as expected.

It is not contradicting that the memory used by the members of the struct are contiguous?.

Kintaro Oe
  • 161
  • 1
  • 5

1 Answers1

2

For efficiency (primarily speed of execution), the compiler will align your int variables on a 4-byte boundary. The layout of your struct is therefore:

name     - 50 bytes
padding  - 2 bytes
tt       - 4 bytes
gg       - 4 bytes
------------------
total     60 bytes
------------------
Paul Sanders
  • 24,133
  • 4
  • 26
  • 48
  • 2
    the second question of this faq: http://c-faq.com/struct/align.esr.html answered my question as well, thank you – Kintaro Oe Aug 22 '20 at 00:26