简体   繁体   中英

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...

EDIT1

With extra braces I get the error: 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 .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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