NO

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

Offline PabloMack

  • Member
  • *
  • Posts: 14
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: 1758
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.

Offline PabloMack

  • Member
  • *
  • Posts: 14
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.