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++ 的加分。
谢谢!
最佳答案
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
关于c++ - 如何创建静态分配的动态大小的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13037806/