In C99 6.2.5 P27
All pointers to structure types shall have the same representation and alignment requirements
as each other. All pointers to union types shall have the same representation and
alignment requirements as each other. Pointers to other types need not have the same
representation or alignment requirements.
What does this mean?
All pointers to structure types shall have the same representation and alignment requirements as each other.
And what is the reason for this exception?
Pointers to other types need not have the same representation or alignment requirements.
I’d appreciate an explanation with relevant examples.
It means that you can store any pointer-to-structure value in any other pointer-to-structure variable, and in the process you create a valid pointer object, and you can recover the original pointer from the intermediate variable. By contrast, you are not allowed to use a pointer of a different category as an intermediate. For example:
The
memcpys are OK because bothpandqhave the same size and alignment, because they are both pointers-to-structs. The same is true for two pointers-to-union, or for two pointers-to-int, but you cannot mix categories.Here’s another, very contrived, but valid example:
This program would not be valid if the function parameter of
fwere a pointer of a different category (say a pointer-to-union or pointer-to-int).The only pointer type that any object pointer can be converted to and back is
void *. (So we could have made the parameter offavoid *. This is arguably the most common style. But it’s conceivable that making it a struct pointer is more efficient and thus preferable on some platforms.)