Casting one C structure into another

memcpy(&vector, &acceleration, sizeof(Vector3d));

Please note that this works only, if the physical layout of the structs in memory are identical. However, as @Oli pointed out, the compiler is not obliged to ensure this!


You could use a pointer to do the typecast;

vector = *((Vector3d *) &acceleration);

You use an utility function for that:

void AccelerationToVector( struct CMAcceleration* from, struct Vector3d* to )
{
     to->x = from->x;
     to->y = from->y;
     to->z = from->z;
}

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.

Tags:

C

Struct

Casting