我目前正在为下一个星期一进行的测试进行练习考试,我遇到了让我感到困惑的事情!
我有以下结构:
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;
}
任何帮助都会被提升!
答案 0 :(得分:2)
首先,您需要将名称strcpy转换为s-> name。
strcpy(s->name, "Name ...");
您可以将s2初始化为
s->description.s2.z = 0;
s->description.s2.base.x = 0;
s->description.s2.base.y = 0;
您可以在书中阅读更多关于工会的信息。你也可以看这里
http://c-faq.com/struct/union.html
答案 1 :(得分:2)
你可以这样做:
s->description.s2.base.x=1;
s->description.s2.base.y=2;
s->description.s2.z=3;
正如您所看到的,语法有时会变得有点沉重,因此定义用于访问指向结构的指针的单个坐标的函数可能是有意义的:
float getX(Shape *s) {
if (dimensions == 2) {
return s->structure.s1.x;
} else {
return s->structure.s2.base.x;
}
}
void setX(Shape *s, float x) {
if (dimensions == 2) {
s->structure.s1.x = x;
} else {
s->structure.s2.base.x = x;
}
}
// Define similar functions for Y and Z
现在您的初始化例程将更改为更具可读性
setX(s, 1);
setY(s, 2);
setZ(s, 3);
答案 2 :(得分:1)
Shape *createShape3D(float x, float y, float z, char *name) {
Shape *s = (Shape *) malloc(sizeof(Shape));
s->dimensions = 3;
s->name = malloc (strlen(name) + 1);
strcpy(s->name, name); // Copy the value of name
s->description.s2.base.x = x;
s->description.s2.base.y = y;
s->description.s2.z = z;
return s;
}
另外,请确保在释放s->name
之前释放Shape* s
的内存