现在I found a way为了静态初始化我的项目数组,我需要一个更复杂的结构,而不是 char* 作为值,我需要一个结构(名为atom_s)。
typdef struct atom_s {
const char *val;
const char *filter;
} atom_t;
struct
{
const char *key;
const atom_t **values;
} key_to_values[] =
{
{ .key = "foo", .values = (const atom_t *[]) { NULL } },
{ .key = "bar", .values = (const atom_t *[]) { { .val = "foo", .filter = "bar" }, NULL } },
};
问题是:我不知道如何在上面的数组声明中初始化一个atom_s,或者是否可能。 数组的第二行(key = "bar")无法编译:
warning: braces around scalar initializer
warning: (near initialization for '(anonymous)[0]')
error: field name not in record or union initializer
最佳答案
{
.key = "bar",
.values = (const atom_t *[]) {
(const atom_t []) {
{ .val = "foo", .filter = "bar" }
// how is the user going to know this array has one element?
},
NULL
}
},
values
指向的数组中的每个元素都指向一个 atom_t
数组(最后一个除外,它为 null)。您可能还需要某种方法来终止每个内部数组,除非它们的长度始终相同。
关于c - C 语言第 2 级数组的理想数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13192427/