[英]initializing an array of struct in C doesn't work as expected
为什么这不起作用:
#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" };
和我不知道为什么...我很困惑...
编辑1
使用多余的花括号,我得到了错误: 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
既然你已经typedef
版tPortMap
。
tPortMap c_portMap[] = { { 0, "test" }, { 1,"test" } };
^^ ^^
使用时
struct tPortMap c_portMap[] = { { 0, "test" }, { 1,"test" } };
编译器认为您正在声明一个新的struct
,它显然是不完整的。
尝试以下方法:
#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.