Structure Initialization

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vinayict
    New Member
    • Apr 2010
    • 1

    #1

    Structure Initialization

    I am unable to understand why I am not able to initialize a global structure variable in the main function, while if I declare a local structure in the main function then I am able to initialize the variable.

    #include <stdio.h>
    typedef struct abc
    {
    int a;
    int b;
    int c;
    } s1;

    s1 vin;
    void main ()
    {
    vin = {10,20,40};
    printf(" The values are a = %d, b= %d, C = %d", vin.a,vin.b,vin .c);

    }

    Gives a error syntax error before vin = {10,20,30};

    While if I declare vin local variable then there is no compilation error and program is running fine.

    #include <stdio.h>
    typedef struct abc
    {
    int a;
    int b;
    int c;
    } s1;

    void main ()
    {
    s1 vin = {10,20,40};
    printf(" The values are a = %d, b= %d, C = %d", vin.a,vin.b,vin .c);

    }
    Output :The values are a = 10 , b=20, c=30;

    Please help where I am wrong in first program ...
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    This syntax:

    Code:
    vin = {10,20,40};
    is initialization syntax and only works if the variable is being created. In your case the variable has already been created before main starts. Inside main() you would use the member syntax:

    Code:
    vin.a = 10;
    vin.b = 20;
    vin.c = 40;

    Comment

    Working...