简体   繁体   English

在C中初始化结构数组无法按预期工作

[英]initializing an array of struct in C doesn't work as expected

Why would this not work: 为什么这不起作用:

#define PORT_ID_MAX_CHAR                6

typedef struct  {
    int phys;
    char name[PORT_ID_MAX_CHAR];
}tPortMap;

struct tPortMap c_portMap[] = { 0, "test" }, { 1,"test" };

GCC barks at me saying myfile.c:8:46: error: expected identifier or '(' before '{' token struct tPortMap c_portMap[] = { 0, "test" }, { 1,"test" }; and I don't know why... I'm puzzled... GCC吠叫我说myfile.c:8:46: error: expected identifier or '(' before '{' token struct tPortMap c_portMap[] = { 0, "test" }, { 1,"test" };和我不知道为什么...我很困惑...

EDIT1 编辑1

With extra braces I get the error: struct tPortMap c_portMap[] = {{ 0, "test" }, { 1,"test" }}; 使用多余的花括号,我得到了错误: struct tPortMap c_portMap[] = {{ 0, "test" }, { 1,"test" }};

myfile.c:8:17: error: array type has incomplete element type struct tPortMap c_portMap[] = {{ 0, "test" }, { 1,"test" }};

You need another pair of braces that surround the data for the elements of the array. 您还需要另一对括号,用于围绕数组元素的数据。

Also, you don't need to use struct tPortMap since you have already typedef ed tPortMap . 此外,您不需要使用struct tPortMap既然你已经typedeftPortMap

tPortMap c_portMap[] = { { 0, "test" }, { 1,"test" } };
                       ^^                            ^^

When you use 使用时

struct tPortMap c_portMap[] = { { 0, "test" }, { 1,"test" } };

the compiler thinks you are declaring a new struct , which obviously is not complete. 编译器认为您正在声明一个新的struct ,它显然是不完整的。

Try this instead: 尝试以下方法:

#include <stdio.h>
#define PORT_ID_MAX_CHAR                6

typedef struct tPortMap {
    int phys;
    char name[PORT_ID_MAX_CHAR];
}tPortMap;

int main(void)
{
    tPortMap c_portMap[] = { { 0, "test" }, { 1,"test" } };

    printf("%s\n", c_portMap[0].name);
    return 0;
}

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

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