[英]How can I create a statically allocated dynamically sized array?
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
};
As you can see in the code, I want to create a statically allocated but dynamically sized array. 正如您在代码中看到的那样,我想创建一个静态分配但动态大小的数组。 I know how to loop through the data, its just that the compiler barfs at the declaration.
我知道如何遍历数据,只是编译器在声明中bar倒了。 While I am looking for a C solution, bonus points for C++ in addition.
当我在寻找C解决方案时,除了C ++外,还有积分。
Thanks! 谢谢!
C solution requires extra variables for defining internal arrays: 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++ solution - requires std::vector<>
- however it is not statically
allocated, but dynamically, and it does not requires terminator: 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
In C++11 you can use initializer lists . 在C ++ 11中,可以使用初始化程序列表 。 You can define a
DictionaryArray
class with a constructor that takes one of these, and then write 您可以使用采用其中之一的构造函数定义
DictionaryArray
类,然后编写
DictionaryArray myArray({ /* some list */ });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.