Cast between two equivalent C structs

c, casting, struct

Solution

There's no such thing as "cast" for struct types in C language. C language only supports casts for scalar types and `void`.

When any other type is used inside `()`, it is no longer a cast. It can only be valid as a part of compound literal syntax. Compound literals is a completely different feature of C language, not related to any casts. For example, this would be correct

struct Position q = (struct Position) { 1, 2 };

In your case you apparently need a reinterperting sequence

q = *(struct Position *) &p;

C language states that this sort of access is considered valid, as long as your struct declarations are indeed synchronized. You can also consider simply `memcpy`-ing one object to the other.

Problem

When compiling the following code : ``` struct Point { int x; int y; }; struct Position { int x; int y; }; struct Point p = {1, 2}; struct Position q = (struct Position)p; ``` An error occurs : error: used type 'struct Position' where arithmetic or pointer type is required Isn't there some way to cast between different `struct` instances when those `struct` actually have the same definition ?

Original source

Related problems