首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C中初始化结构数组不像预期的那样工作

在C中初始化结构数组不像预期的那样工作
EN

Stack Overflow用户
提问于 2016-03-14 18:28:20
回答 2查看 58关注 0票数 0

为什么这不起作用:

代码语言:javascript
复制
#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" }};

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-14 18:33:23

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

而且,您不需要使用struct tPortMap,因为您已经使用了typedefed tPortMap

代码语言:javascript
复制
tPortMap c_portMap[] = { { 0, "test" }, { 1,"test" } };
                       ^^                            ^^

当你使用

代码语言:javascript
复制
struct tPortMap c_portMap[] = { { 0, "test" }, { 1,"test" } };

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

票数 2
EN

Stack Overflow用户

发布于 2016-03-14 18:44:26

试一试:

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35995239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档