Omer Omer - 9 months ago 76
C++ Question

Aligning memory address of specific pragma packed struct member?

I have a struct with data members with types of different lengths (some ints, some words, some just single bytes). The struct is packed (using #pragma pack(1)).

My question is: Is it possible to have one of the struct's data members memory address be aligned in memory (for example, have the address be divisable by 16)?

I know it is possible to align the whole struct (or in other words, its first member) using attribute. I want to know if it's possible to align a specific member and not just the first one.

Basically I need the struct to be packed (every member follows the previous one without padding) and I need that the address of one of the members, not the first one, be divisable by 16.


There doesn't seem to be any possibility to align structures with an offset. You must create the offset (padding) by yourself.

typedef struct __attribute__((packed)) special_align {
    char misc[3];
    int align_me;

typedef struct __attribute__((packed, aligned(16))) pad_container {
    char padding[13];   //16-3
    struct special_align data;

Of course accessing the struct will become more cumbersome. If you don't want to calculate by hand how much padding you need, you can use the offsetof() macro. In the example offsetof(struct special_align,align_me) will return 3, that is to be substracted from the align size. (of course if the offset is greater than align, you must use a corresponding pad size multiplier. `

 pad_size = (sizeof(special_align) * align_size - offsetof(special_align,align_me)) % align_size;