Casting one C structure into another

前端 未结 8 674
再見小時候
再見小時候 2020-11-27 03:30

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

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


typedef struc         


        
8条回答
  •  醉梦人生
    2020-11-27 03:58

    This is achieved easily through a union:

    typedef struct {
          double x;
          double y;
          double z;
    } CMAcceleration;
    
    typedef struct {
        double x;
        double y;
        double z;
    } Vector3d;
    
    typedef union {
        CMAcceleration acceleration;
        Vector3d vector;
    } view;
    
    int main() {
        view v = (view) (Vector3d) {1.0, 2.0, 3.0};
        CMAcceleration accel = v.acceleration;
        printf("proof: %g %g %g\n", accel.x, accel.y, accel.z);
    }
    

提交回复
热议问题