0

I have a struct in c such that,

typedef struct {
    char ch;
    int num;
} structB;

Now by how many bytes should the addresses of ch and num differ based on the addresses that they are stored on? When I run sizeof, the size of the structB is 8, but char is supposed to be 1 byte? So, should the elements inside the struct still differ by 4 bytes? I am a bit confused on this.

Note: The question seems to be closed due to it being similar as another one, but I am still confused regarding padding. So could someone explain with reference to the structB provided above?

xhienne
  • 5,738
  • 1
  • 15
  • 34
  • 1
    Why do you want to know? This is determined by the compiler and possibly by a packing setting. – Paul Ogilvie Feb 12 '21 at 09:36
  • You can use pointer math to compute the difference. Cast pointers to your variables to byte pointers and use the difference. Anyway your confusion is due to variables type alignment. Presumably your compiler aligns `int` on 4 bytes boundary, so the compiler adds 3 padding bytes between `ch` and `num` making structure size 8. – Frankie_C Feb 12 '21 at 09:37
  • The compiler probably aligns members on 4 bytes. – Paul Ogilvie Feb 12 '21 at 09:37
  • Everything you need to know about padding and alignment is [on Wikipedia](https://en.wikipedia.org/wiki/Data_structure_alignment). Use `offsetof(structB, num)` to figure out the amount of padding added by your compiler between `.ch` and `.num`. If your structure is 8 bytes long, it's probably 3 bytes of padding. – xhienne Feb 13 '21 at 20:11

0 Answers0