I’m trying to determine if two structs are compatible. In my case, it’s not clear to me if pointers of different types are considered compatible. In the following example, are structs t1
and t2
compatible?
typedef struct string {
size_t len;
char val[]; // flexible array member
} string;
struct t1 {
const char *name;
};
struct t2 {
string *name;
};
Since they are both pointers (and not pointers to functions), they have the same size and alignment, which is a prerequisite. But I do not understand all the other rules well enough to know if these are layout compatible. Knowing if they are layout-compatible factors into things like the common initial sequence for unions, casting pointers to compatible types, etc.
My guess is that no, they are not compatible. I would guess the pointers would have to point to the same or compatible types, and this is neither.
2
Since they are both pointers (and not pointers to functions), they have the same size and alignment, which is a prerequisite.
This premise is false. Nothing in the C standard requires different types of pointers to have the same size or alignment requirements except, per C 2018 6.2.5 28:
-
A pointer to
void
shall have the same representation and alignment requirements as a pointer to a character type. -
Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements.
-
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.
The paragraph ends with the explicit statement:
Pointers to other types need not have the same representation or alignment requirements.
they have the same size and alignment,
The 2 pointer types can have the same size and layout on OP’s machine, yet that is not certain across all compliant C implementations.
The 2 struct
s will have the same alignment requirements.
Highly portable code does not rely on same size.