结构体/联合体初始化混淆

3

我目前正在练习下周一要考试的测试,我遇到了一些让我困惑的事情!

我有以下结构体:

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;
}

如果能够得到您的帮助,将不胜感激!


将2D或3D点描述为“形状”似乎有些奇怪。您可能还会认为description是一个非常长的名称。如果您使用C2011,可以考虑使用匿名联合。 - Jonathan Leffler
3个回答

2

1
你可以这样做:

 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);

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;
}

同时,在释放Shape* s之前,确保先释放s->name所占用的内存。


你的 s->name 存在内存泄漏。 - user93353
谢谢!我没有注意到,我只是简单地复制了用户帖子中的内容,并想展示如何设置xyz的值。无论如何,我已经更新了答案并设置了name - Tuxdude
现在,在 s->name 中接受 strcpy 的返回是多余的。 - user93353
谢谢!又一个打字错误,已经修复了。 - Tuxdude

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接