我试图在 main() 中初始化一个结构类型的数组,但编译器返回错误 field designator cannot initialize a non-struct, non-union type
我的代码:
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.
最佳答案
你少了一对牙套。试试这个:
struct details a [] = {{
.author = "Narsimha",
.title = input
}};
外括号用于定义数组。内部大括号用于 struct
。
关于c - 如何使用 DOT 运算符初始化结构类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51472987/