Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting one C structure into another

Tags:

c

casting

struct

I have two identical (but differently named) C structures:

typedef struct {       double x;       double y;       double z; } CMAcceleration;   typedef struct {     double x;     double y;     double z;    } Vector3d; 

Now I want to assign a CMAcceleration variable to a Vector3d variable (copying the whole struct). How can I do this?

I tried the following but get these compiler errors:

vector = acceleration;           // "incompatible type" vector = (Vector3d)acceleration; // "conversion to non-scalar type requested" 

Of course I can resort to set all members individually:

vector.x = acceleration.x; vector.y = acceleration.y; vector.z = acceleration.z; 

but that seems rather inconvenient.

What's the best solution?

like image 737
Ortwin Gentz Avatar asked Oct 22 '10 10:10

Ortwin Gentz


People also ask

Can we assign a structure to another structure?

Yes, you can assign one instance of a struct to another using a simple assignment statement. In the case of non-pointer or non pointer containing struct members, assignment means copy. In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.

What is C type casting?

Type Casting is basically a process in C in which we change a variable belonging to one data type to another one. In type casting, the compiler automatically changes one data type to another one depending on what we want the program to do.

Does C support type casting?

C programming language is best known for offering various types of functionalities and features to the programmers. C also allows the programmers to do type casting. Typecasting and Type conversion are different things. In C, typecasting is a way to simply change the data type of a variable to another data type.


2 Answers

That's your only solution (apart from wrapping it into a function):

vector.x = acceleration.x; vector.y = acceleration.y; vector.z = acceleration.z; 

You could actually cast it, like this (using pointers)

Vector3d *vector = (Vector3d*) &acceleration; 

but this is not in the specs and therefore the behaviour depends on the compiler, runtime and the big green space monster.

like image 133
Georg Schölly Avatar answered Sep 26 '22 10:09

Georg Schölly


You could use a pointer to do the typecast;

vector = *((Vector3d *) &acceleration); 
like image 21
David Gelhar Avatar answered Sep 26 '22 10:09

David Gelhar