Search code examples
cstructcastingansi-c

Struct pointer compatibility


Suppose we have two structs:

typedef struct Struct1
{
    short a_short;
    int id;
} Struct1;

typedef struct Struct2
{
    short a_short;
    int id;
    short another_short;
} Struct2;

Is it safe to cast from Struct2 * to Struct1 * ? What does the ANSI spec says about this? I know that some compilers have the option to reorder structs fields to optimize memory usage, which might render the two structs incompatible. Is there any way to be sure this code will be valid, regardless of the compiler flag?

Thank you!


Solution

  • struct pointers types always have the same representation in C.

    (C99, 6.2.5p27) "All pointers to structure types shall have the same representation and alignment requirements as each other."

    And members in structure types are always in order in C.

    (C99, 6.7.2.1p5) "a structure is a type consisting of a sequence of members, whose storage is allocated in an ordered sequence"