Reputation: 23
If I had a struct consisting only of short unsigned integers, that would be stored in contiguous memory locations of the same size; the same also applies if I have an array of short unsigned integers. How would they be any different? Is it how they are accessed? I am aware that an array is accessed by using a pointer to reference the starting value of the array while an array operator sets an offset from that memory location, does the same apply to structs or are structs accessed by using the memory location for each piece of data?
Upvotes: 2
Views: 543
Reputation: 134286
No, they need not be the same and most likely, they are not.
In case of structure members, there can be padding between the members. So, it is not guaranteed that consecutive members will reside in contiguous memory. In this case, based on implementation, pointer arithmetic using the address of the first element may or may not work be valid.
Quoting relevant parts of C11
standard, chapter §6.7.2.1/p15, Structure and union specifiers,
[..] There may be unnamed padding within a structure object, but not at its beginning.
and
chapter §6.5.3.4, sizeof
operator,
[...] When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, including internal and trailing padding.
In case of an array, however, all members are guaranteed to reside in contiguous memory and pointer arithmetic is deterministic.
Upvotes: 2