【问题标题】:initializing an array of struct in C doesn't work as expected在 C 中初始化结构数组不能按预期工作
【发布时间】:2016-03-14 18:28:20
【问题描述】:

为什么这不起作用:

#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 对我咆哮说myfile.c:8:46: error: expected identifier or ‘(’ before ‘{’ token struct tPortMap c_portMap[] = { 0, "test" }, { 1,"test" };,我不知道为什么......我很困惑......

EDIT1

使用额外的大括号我得到了错误: 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" }};

【问题讨论】:

  • struct tPortMap c_portMap[] = {{ 0, "test" }, { 1,"test" }}; 解决问题了吗?
  • 我差点错过了6 ...
  • 请参阅上面的EDIT1
  • 不是struct tPortMap,只是tPortMap
  • 是的,我愿意,它们都在同一个文件中。

标签: c struct initialization


【解决方案1】:

您需要另一对大括号来围绕数组元素的数据。

另外,您不需要使用struct tPortMap,因为您已经拥有typedefed tPortMap

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

当你使用

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

编译器认为你在​​声明一个新的struct,这显然是不完整的。

【讨论】:

  • 请参阅上面的EDIT1
【解决方案2】:

试试这个:

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-23
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多