简体   繁体   中英

How to initialize array of struct that have a pointer to array of struct?

This is my struct:

struct ini_entry {
    const char *section;
    const char *name;
};

struct ini_parser {
    bool (*parser) (void *ctx, const char *file, struct collection_item **vals, int nval);
    struct ini_entry *entries;
};

This is my initializer:

static struct ini_parser parsers[] = {
    {NULL, &(struct ini_entry) {"test", "xxx"}}
};

I need to add more ini_entry in the initializer. Is there anyway to do this with static initialization within a single declaration?

Sorry for my English.

Firstly, struct ini_entry *entries; should be struct ini_entry const *entries; if you intend to initialize it with a struct literal (and even if you don't).

But this sort of layout may be easier to read:

struct ini_entry const foo_entries[] = {
    { "test", "xxx" },
    { "flub", "yyy" },
    { "gnas", "zzz" },
    { NULL, NULL }     // list terminator presumably required
};

struct ini_parser const parsers[] = {
    { "foo", foo_entries },
    { "bar", bar_entries }
};

Note that it would be possible to use a counted list instead of using an end sentry; the length of the list is a compile-time constant (sizeof foo_entries / sizeof foo_entries[0]) which you could put as a third member of struct ini_parser .

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