3

I want to create a new structure that is the combination of two identical structures. Each of these sub structures includes one scalar double and a three dimensional array. However, when I try to initialize the structure I am getting errors when attempting to give the array its values.

I don't have compilation errors, but when I try to look into the values of the array within the nested structure, I see very completely wrong insane numbers.

Do you know what I am doing wrong here?

typedef struct quackStruct {
    double s;
    double v[3];
} quackStruct;

typedef struct dualquackStruct {
    quackStruct q1;
    quackStruct q2;
} dualquackStruct;

int main() {
    quackStruct duck1 = { .s = 0.0, .v = { 0.5,4.0,2.1 } };
    quackStruct duck2 = { .s = 0.85, .v = { 20.0, 10.0, -5.0 } };

    /* I tried this... but it didn't work
    dualquackStruct ducks = { duck1, duck2 }; */

    /* this didn't work either */
    dualquackStruct ducks = { .q1.s = 0.0, .q1.v = { 0.5, 4.0, 2.1 },
                              .q2.s = 0.85, .q2.v = { 20.0, 10.0, -5.0 } };

    printf("%f\n", ducks.q1.s);
    printf("%f\n", ducks.q1.v[0]);
    printf("%f\n", ducks.q1.v[1]);
    printf("%f\n", ducks.q1.v[2]);
    printf("%f\n", ducks.q2.s);
    printf("%f\n", ducks.q2.v[0]);
    printf("%f\n", ducks.q2.v[1]);
    printf("%f\n", ducks.q2.v[2]);

    return 0;
}
einpoklum
  • 118,144
  • 57
  • 340
  • 684
jdhabez
  • 41
  • 4

1 Answers1

4

Your first line does compile. But - you can't define the same variable twice...

In your second line, you need to perform nested-initialization of the q1 and the q2 structure within braces, not to go two-levels down with .firstlevelfield.secondlevelfield.:

dualquackStruct ducks = { .q1 = { .s = 0.0,  .v = { 0.5,  4.0,  2.1} },
                          .q2 = { .s = 0.85, .v = {20.0, 10.0, -5.0} } };

See both lines (after the correction) compiling (GodBoot).

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • You **must** add the `=` after `.q1` and `.q2`. As posted, the code is not C conformant, it only compiles as C++. Add `-x c` in Godbolt's options to force C compilation. – chqrlie Apr 05 '19 at 14:42
  • 1
    You might also show the simpler alternative: `dualquackStruct ducks = { { 0.0, { 0.5, 4.0, 2.1} }, { 0.85, {20.0, 10.0, -5.0} } };` – chqrlie Apr 05 '19 at 14:42
  • @jdhabez: Note my edit; I forgot a couple of `=` signs. – einpoklum Apr 05 '19 at 15:24