I wonder if it is safe, according to the C99 standard, to interpret such a struct:
struct my_struct_t {
int a;
int b;
int c;
};
as an int[3]. I.e. is this code snippet sane for all ABIs?
struct my_struct_t f;
int *i = &f.a;
i[0] = 1; // f.a == 1
i[1] = 2; // f.b == 2
i[2] = 3; // f.c == 3
As far as I understand the standard, the compiler is allowed to add padding after members in a struct, but there must not be any padding inside an array. Am I getting that right? (If I am, then the code example would yield undefined behavior.)
The only real "answer" to this is a citation:
C11, 6.7.2.1:
There may be unnamed padding within a structure object, but not at its beginning. (paragraph 15)
There may be unnamed padding at the end of a structure or union. (paragraph 17)
C11, 6.2.5:
An array type describes a contiguously allocated nonempty set of objects with a particular member object type (paragraph 20)
Since the subscript operator is exactly equivalent to a pointer arithmetic operation, it cannot take account of padding (external to the type of the target object, anyway) where any may exist, and in a struct, it may.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With