Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast between two equivalent C structs [duplicate]

Tags:

c

casting

struct

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 ?

like image 526
Weier Avatar asked Aug 17 '26 08:08

Weier


2 Answers

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.

like image 102
AnT Avatar answered Aug 19 '26 17:08

AnT


You can do this using type punning, since the standard permits that two structures sharing a common initial sequence be aliased as long as only the common initial members are accessed:

struct Position q = *(struct Position *)&p;

or even better

union {
    struct Position pos;
    struct Point pt;
} pun;

pun.pt = p;
struct Position q = pun.pos;

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!