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

任何帮助将不胜感激!

4

3 回答 3

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

http://c-faq.com/struct/initunion.html

http://c-faq.com/struct/taggedunion.html

于 2013-03-02T02:56:10.017 回答
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);
于 2013-03-02T02:59:03.987 回答
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

于 2013-03-02T02:59:41.590 回答