siods333333
siods333333

Reputation: 27

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 : '}'

Upvotes: 2

Views: 82

Answers (1)

dbush
dbush

Reputation: 223972

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

Upvotes: 1

Related Questions