Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct/union initialization confusion

Tags:

c

struct

unions

I'm currently doing practice exams for a test I will have next monday and I came across something that confused me!

I have the following structs:

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;

I have to make a function that 'creates' a shape with the following signature:

Shape *createShape3D(float x, float y, float z, char *name);

Because I'm dealing with an union of structs, I'm not quite sure how to initialize all the fields I need!

Here's what I have so far:

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

Any help would be apprectiated!


1 Answers

First you need to strcpy name to s->name.

strcpy(s->name, "Name ...");

You can initialize s2 as

s->description.s2.z = 0;
s->description.s2.base.x = 0;
s->description.s2.base.y = 0;

You can read up more on unions in a book. You can also look here

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

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

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

like image 183
user93353 Avatar answered May 18 '26 08:05

user93353



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!