Suppose this code:
unsigned char list[3] = { 1, 2, 3 };
struct _struct{
unsigned char a;
unsigned char b;
unsigned char c;
} *s;
s = ( _struct * ) list;
Can I assume that always s->a == 1, s->b == 2, s->c == 3 ?
Or it will depend on the system’s endianness or memory alignment?
Let’s dissect this.
In all cases,
sizeof(char) == 1, and thelistarray will have its three members at memory locationslist,list + 1, andlist + 2.The situation with the
structis not quite as clear. The Standard guarantees that the members will be allocated in increasing memory locations, but not that they will be contiguous. The compiler is free to introduce padding between members, and padding at the end.Therefore,
s->a == 1will always be true. If the implementation puts theunsigned chars in thestructadjacent (and most will), then the other equalities will necessarily be true.By the way, calling a
struct_structmay cause problems. A name beginning with an underscore in the global namespace is reserved for the implementation.