NO

Author Topic: Can I Relax Alignment on struct members?  (Read 3022 times)

PabloMack

  • Guest
Can I Relax Alignment on struct members?
« on: March 28, 2020, 06:01:55 PM »
I have created a struct that uses types of odd byte sizes. Seems that the compiler wants to pad every member to 8 bytes. Can I relax the alignment constraints on struct members so that the size of the structure will always be the sum of the the declared sizes of all its members with no padding? It is perfectly fine for them to be misaligned because I will explicitly pad with values to bring the data structure to the size I want it to be which will probably be 128 bytes.

If I can't do it then I will have to resort to a lot of casts and explicit offset values to bypass the error checking straight jacket.
« Last Edit: March 28, 2020, 06:05:11 PM by PabloMack »

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2113
Re: Can I Relax Alignment on struct members?
« Reply #1 on: March 28, 2020, 10:40:50 PM »
use packing pragmas.

Code: [Select]
#pragma pack(1)    //pack structures on byte boundary
typedef struct
{
    char a[3];
    short b;
} PackedStruct;
#pragma pack()    //restore standard packing

PackedStruct my_struct;
printf("%u bytes\n", sizeof(my_struct));

Will print 5 bytes.
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide

PabloMack

  • Guest
Re: Can I Relax Alignment on struct members?
« Reply #2 on: March 30, 2020, 03:25:34 PM »
Thanks. I've never used pragmas in my entire 34 years of writing tons of C code
for many different compilers.  But I guess this will be the place to start.