简体   繁体   中英

Issue initializing array inside struct

I'm trying to get a structure, which contains an integer and a pointer to another structure. This second structure is just an array of 2 strings and an array of 2 numbers.

What am I doing wrong here?

struct folder {
    char **filenames_array;
    int *images_array;
};

struct display {
    int pos_y;
    struct folder current_folder;
};

struct display g_display = {
    .pos_y = 0,
    .current_folder = {
        .filenames_array = {"002.jpg", "003.jpg"},
        .images_array = {0, 0},
    }
};

I'm getting those errors:

error C2143: syntax error : missing '}' before '.'
error C2143: syntax error : missing ';' before '.'
error C2059: syntax error : '.'
error C2143: syntax error : missing ';' before '{'
error C2447: '{' : missing function header (old-style formal list?)
error C2059: syntax error : '}'
error C2143: syntax error : missing ';' before '}'
error C2059: syntax error : '}'

You can do this with compound literal syntax:

struct display g_display = {
    .pos_y = 0,
    .current_folder = {
        .filenames_array = (char *[]){"002.jpg", "003.jpg"},
        .images_array = (int []){0, 0},
    }
};

Alternately, if you know your arrays will always have two elements, you can keep the current initializer syntax and declare the arrays as actual arrays instead of pointers:

struct folder {
    char *filenames_array[2];
    int images_array[2];
};

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