简体   繁体   English

如何使用DOT运算符初始化struct类型的数组

[英]How to Initialise array of type struct with DOT operator

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: 我正在尝试初始化main()中的struct类型的数组,但是编译器返回错误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.

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 . 内部花括号用于该struct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM