Search code examples
cstructinitializationdeclaration

How do I initialize a struct in C


I got a comment on how I initialize my struct in C, saying that It does not work and it does not compile either.

This is how I create and initialize a structure in C.

struct {
int a; 
int b;
char arr[3];
.
.
.
} data = {
.a = 1, 
.b = 2
};

main(){
/* do stuff */
}

This how I initialize my struct and It works and compiles. Yet I got a comment saying this would compile for c++ but not for C. Can someone ensure me that this correct alternative? If not why is it compiling with no errors?


Solution

  • I think there is a typo in the declaration of the data member arr. Instead of

    char [3]arr;
    

    you have to write

    char arr[3];
    

    You may not initialize an array with empty braces. So write for example

    struct {
    int a; 
    char arr[3];
    .
    .
    .
    } data = {
    .a = 1, 
    .arr = { 0 }
    };
    

    In fact it is enough to write

    struct {
    int a; 
    char arr[3];
    .
    .
    .
    } data = {
    .a = 1
    };
    

    The array implicitly will be initialized with zeroes.