I use __attribute__((packed)) to avoid filling the string. The following code works fine, but when I add another int member inside the structure, the compiler populates my structure.
#include <stdio.h> struct test { int x; char c1; char c2; char c3; char c4; char c5; // int d; Pads if I uncomment } __attribute__((packed)) obj = {50,'X','Y','Z','A','B'}; int main () { struct test *ptr= &obj; char *ind = (char *) &obj; printf("\nLet see what is the address of obj %d", ptr); printf("\n Size of obj is : %d bytes ", sizeof(obj)); printf("\nAddress of x is %d", &ptr->x); printf("\nAddress of c1 is %d", &ptr->c1); printf("\nAddress of c2 is %d", &ptr->c2); printf("\nValue of x is %d", ptr->x); printf("\nAddress of x is %c", ptr->c1); printf("\nFetching value of c4 through offset %c", *(ind+7)); }
The above code works as expected, and the size of obj is 9 bytes (it had 12 bytes to populate).
However, when I uncomment the int d in my structure, the code outputs:
Obj size: 16 bytes
instead of the expected 13 (9 + 4) bytes.
What's wrong?
c struct
theartist33
source share