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?
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.
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.
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.
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.
You could use a pointer to do the typecast;
vector = *((Vector3d *) &acceleration);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With