0

I meet two structs:

struct s1{
  int i;
  int j;
  char c;}

struct s2{
  int i;
  char c1;
  int j;
  char c2;}

the textbook says c in S1 only occupies 1 byte,whereas c2 in S2 occupies 4 bytes, why is this? Is it because c1 has to occupy 4 bytes, and they have the same type?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847

1 Answers1

0

There are 3 bytes of padding after s1::c, same as after s2::c1, in the i386 System V ABI's struct layout rules. (And most normal ABIs.)

The total struct size has to be a multiple of its alignof() for arrays to work: structs in contiguous memory, each one taking sizeof(struct s1), but also the start of each struct being aligned so that the int members are aligned.

Look at the sizeof() and alignof() of both types, and of int vs. char. sizeof(char) = 1 as defined by ISO C, and in i386 SysV, sizeof(int) = alignof(int) = 4.

If you had a struct { char foo[8]; char c; }; then it's total size would only be 9 bytes, because alignof(char) = 1.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • I understand that s1 should have 3 more bytes like this: struct s1 a[4] . But if I dont declare a, is it still the same?I meet this in CS:APP. Here is the quote: If we pack this structure into 9 bytes, we can still satisfy the alignment requirements for fields i and j by making sure that the starting address of the structure satisfies a 4-byte alignment requiremen. – APOSTATE LOYAL Aug 30 '20 at 04:10
  • 1
    So the total size of an struct should always be a multiple of its alignment, no matter whether you declare an array of this struct. – APOSTATE LOYAL Aug 30 '20 at 04:17