1

I am trying to initialize an array of type struct within main() but compiler returns error field designator cannot initialize a non-struct, non-union type My Code:

struct details{
    const char *author;
    const char *title;
};


int main()
{
    const char *input = "Data Structures and Algorithm";
    struct details a [] = { 
        .author = "Narsimha", 
        .title = input
    };  
    printf("%s\n", a[0].author);
    printf("%s\n", a[0].title);

    return 0;
}
gcc inputs.c 
inputs.c:16:9: error: field designator cannot initialize a non-struct, non-union type 'struct details []'
        .author = "Narsimha", 
        ^
inputs.c:17:9: error: field designator cannot initialize a non-struct, non-union type 'struct details []'
        .title = input
        ^
2 errors generated.
Aamir Shaikh
  • 345
  • 1
  • 2
  • 13
  • Possible duplicate of [Initializing array of structures](https://stackoverflow.com/questions/18921559/initializing-array-of-structures) – Michael Jul 23 '18 at 06:49

1 Answers1

5

You are missing a pair of braces. Try with this:

struct details a [] = {{ 
        .author = "Narsimha", 
        .title = input
    }};

The outer braces are for defining an array. The inner braces are for the struct.

babon
  • 3,615
  • 2
  • 20
  • 20