c - 如何使用 DOT 运算符初始化结构类型的数组

标签 c

我试图在 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/

相关文章:

c - 必须将 ELF 文件的哪一部分加载到内存中?

c - 内存空间布局/奇怪的内存(堆栈)行为 C/ASM?

java - 是否可以使用 Turbo C/C++ 编译器生成 DLL?

c - 快速排序代码出错但未在错误窗口中显示

c - 删除 list.h 列表的第一个元素

c - MPI 向工作人员发送信息时出现问题

c++ - 如果分配是在堆栈或堆上完成的,那么 free() 和 delete[] 是否重要?

c - 从文件读取并存储到C中的二维数组中

c++ - 函数返回的字符串文字的生命周期

c - 使用调试符号从指令指针查找变量名