我目前正在练习下周一要考试的测试,我遇到了一些让我困惑的事情!
我有以下结构体:
struct shape2d {
float x;
float y;
};
struct shape3d {
struct shape2d base;
float z;
};
struct shape {
int dimensions;
char *name;
union {
struct shape2d s1;
struct shape3d s2;
} description;
};
typedef struct shape Shape;
我需要编写一个函数,用以下签名来“创建”一个形状:
Shape *createShape3D(float x, float y, float z, char *name);
因为我正在处理结构体的联合,所以我不太确定如何初始化我需要的所有字段!
这是我到目前为止拥有的:
因为我正在处理结构体的联合,所以我不太确定如何初始化我需要的所有字段!
Shape *createShape3D(float x, float y, float z, char *name) {
Shape *s = (Shape *) malloc(sizeof(Shape));
s->dimensions = 3;
s->name = "Name...";
// How can I initialize s2?
return s;
}
如果能够得到您的帮助,将不胜感激!
description
是一个非常长的名称。如果您使用C2011,可以考虑使用匿名联合。 - Jonathan Leffler