typedef struct DictionaryEntry_s {
char *key;
char *value;
} DictionaryEntry;
typedef struct Dictionary_s {
char *name;
DictionaryEntry values[0];
} Dictionary;
//How can I do the following:
Dictionary myDictionary[] = {
{"synonyms",
{"good", "cool"},
{"bad", "evil"},
{"awesome", "me"},
{"like", "love"}, //etc....
{0} //terminator
},
{"antonyms",
{"good", "evil"},
{"bad", "good"},
{"awesome", "not me"}, ///...etc
{0} //terminator
},
{0} //terminator
};
正如您在代码中看到的,我想创建一个静态分配但动态大小的数组。我知道如何遍历数据,它只是编译器barfs在声明。虽然我正在寻找一个C解决方案,另外还有C ++的奖励积分。
谢谢!
答案 0 :(得分:3)
C解决方案需要额外的变量来定义内部数组:
typedef struct DictionaryEntry_s {
char *key;
char *value;
} DictionaryEntry;
typedef struct Dictionary_s {
char *name;
DictionaryEntry* values;
} Dictionary;
//How can I do the following:
DictionaryEntry myDictionary0[] = {
{"good", "cool"},
{"bad", "evil"},
{"awesome", "me"},
{"like", "love"}, //etc....
{0} //terminator
};
Dictionary myDictionary[] = {
{"synonyms", myDictionary0},
// ...
{0} //terminator
}; // <-- semicolon was missing here
C ++解决方案 - 需要std::vector<>
- 但它不是statically
分配的,而是动态的,并且它不需要终结符:
struct DictionaryEntry {
char *key;
char *value;
};
struct Dictionary {
char *name;
std::vector<DictionaryEntry> values;
};
//How can I do the following:
Dictionary myDictionary[] = {
{"synonyms",
{
{"good", "cool"},
{"bad", "evil"},
{"awesome", "me"},
{"like", "love"}, //etc....
{0} //terminator
}
},
//...
{0} //terminator
}; // <-- semicolon was missing here
答案 1 :(得分:2)
在C ++ 11中,您可以使用初始化列表。您可以使用构造函数定义DictionaryArray
类,其中包含其中一个,然后编写
DictionaryArray myArray({ /* some list */ });