Search code examples
cstructinitializationinitializer

Error in initializing structure variables


Okay, so this isn't actually the code I was working on. This is an oversimplified code extract that produces the exact same error. Thus, I thought if I could learn why I am getting errors with the simplified code, then I could apply it to my actual code. Thanks for any help/advice in advance!

#include <stdio.h>
int main()
{
    struct fruit
    {
       int apples; 
       int oranges;
       int strawberries;
    };

    int x;
    int y;
    int z;

    x = 1;
    y = 2;
    z = 3;

    struct fruit apples = x;
    struct fruit oranges = y;
    struct fruit strawberries = 4;

    printf("The value is %d or %d", fruit.apples,fruit.strawberries);

    return 0;
}

Solution

  • First of all, you cannot initialize a struct type variable with an int value anyway, you have to use either a brace-enclosed initializer, or initialize each member explicitly.

    That said,

    struct fruit applies 
    struct fruit oranges 
    struct fruit strawberries 
    

    is not how you define a variable of type struct fruit and access the members. The correct way would be

     struct fruit f;
     f.apples = x;
     f.oranges = y;
     f.strawberries= 4;
    

    or, a more precise way,

      struct fruit f = {x,y,4};
    

    or, even cutting down the intermediate variables,

      struct fruit f = {1,2,4};