简体   繁体   English

如何初始化具有指向结构数组的指针的结构数组?

[英]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. 我需要在初始化程序中添加更多的ini_entry Is there anyway to do this with static initialization within a single declaration? 无论如何,在单个声明中使用静态初始化来执行此操作吗?

Sorry for my English. 对不起我的英语不好。

Firstly, struct ini_entry *entries; 首先, struct ini_entry *entries; should be struct ini_entry const *entries; 应该是struct ini_entry const *entries; if you intend to initialize it with a struct literal (and even if you don't). 如果您打算使用struct文字对其进行初始化(即使您没有这样做)。

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 . 列表的长度是一个编译时常量(sizeof foo_entries / sizeof foo_entries[0]) ,您可以将其作为struct ini_parser的第三个成员struct ini_parser

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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