Data alignment of C structures


Traau

CS: There is an issue (3.45) in APP concerning byte offsets of all fields in the following structure.

struct {
  int    *a;
  float  b;
  char   c;
  short  d;
  long   e;
  double f;
  int    g;
  char   *h;
} rec;

Here's the answer from the book, giving cthree bytes of padding, dtwo bytes of padding, and gfour bytes of padding.

field  size  offset
-----  ----  ------
a      8     0
b      4     8
c      1     12
d      2     16
e      8     24
f      8     32
g      4     40
h      8     48

Here is my solution which gives only cone byte of padding and gfour bytes of padding.

field  size  offset
-----  ----  ------
a      8     0
b      4     8
c      1     12
d      2     14
e      8     16
f      8     24
g      4     32
h      8     40

So, what's wrong with my solution? Seems to conform to the alignment rules (EDIT* the "rules" here are just my own simplified conceptual summary, unfinished or general), and all objects are offset by a multiple of the object's size.

Thanks a lot for your explanation.

P__J supports women in Poland

The answer depends on the compiler, platform and compilation options. Some examples:enter image description here

https://godbolt.org/z/4tAzB_

The author of this book did not understand the topic I was concerned about.

Related