#include <stdio.h>
struct Obj {
char a;
uint32_t b;
uint8_t c;
uint64_t d[0];
};
struct Obj1 {
uint64_t d[0];
};
int main() {
uint64_t a[0];
printf("%d\n", sizeof(Obj)); // 16
printf("%d\n", sizeof(a)); // 16
printf("%d\n", sizeof(Obj1)); // 16
//cout << sizeof(Obj) << endl; // 16
//cout << sizeof(a) << endl; // 0
//cout << sizeof(Obj1) << endl; // 0
}
As shown above, why the uint64_t variable within the struct will not be stacked right back after the uint8_t, and more peculiar is that the empty array has zero sizes outside the structure.
It's actually an interview question. The explanation goes like this, though still can't understand.
If there is no fourth field, it should be 4+4+4=12, plus the fourth field is 16, the fourth field does not occupy space, but it will tell the compiler to align by 8 bytes
This usage is often used in the kernel, for example, the following can be directly accessed by subscript
Obj o1; uint64_t array[1024]; // In memory, array immediately follows
o1 o1.d[123]; // can access the elements of array
As noted by comments, this may be only applied in C instead of C++. SO I changed the code to C version.