Coco Coco - 1 month ago 7
C Question

define struct to make two members hold the same value

how to organize the jo struct to make the member c get the value of gpr[0].a when I give a number to gpr[0].a in main function. It seems I can not use '=' to make them hold the same value in the definition of structure.
Don't change the main function, just reorganize the struct jo, get the result ou.c =1, ou.d =2

#include <stdio.h>
#include <stdlib.h>

typedef struct {
union {
double a;
int b;
} gpr[2];
double c, d;
} jo;

int main (int argc, char *argv[])
{
jo ou;

ou.gpr[0].a = 1;
ou.gpr[1].a = 2;

printf("%f\n", ou.c);
printf("%f\n", ou.d);

return 0;
}


any help will be appreciated

Answer

This is being done to test your knowledge of unions. So currently you have a union of a and b in an array of length two. Now we need the gpr[0] to be the same as c and gpr[1] to be the same as d.

So, each member of the array is of length sizeof(double) and there are two of them. So we need a struct that is 2 doubles (c and d) to be unioned with the gpr[2] variable.

Thus this should work:

typedef struct {
     union {
          struct {
              double c;
              double d;
          };
          union {
              double a;
              int b;
          } gpr[2];
   };
} jo;

We have to use anonymous structs and unions or the code has to change for us to reference the members.

Comments