我有以下代码,它没有按预期工作。它可以编译,但在执行时会抛出很多警告和段错误:
#include <stdio.h>
enum output {
A,
B,
C,
D,
};
struct translation {
char *from;
enum output to;
};
struct dictionary {
struct translation *foo;
struct translation *bar;
};
enum language {
ONE,
ANOTHER,
};
struct dictionary languages[] = {
[ONE] = {
.foo = {
{"LF", A},
{"LLF", C},
{"RRF", D},
},
.bar = {
{"L", B},
},
},
[ANOTHER] = {
.foo = {
{"FF", B},
{"RRF", D},
},
.bar = {
{"LF", B},
{"R", C},
{"RR", D},
},
},
};
int main(void)
{
printf("%s\n", languages[ONE].foo[0].from);
return 0;
}
我可能以错误的方式初始化languages
。
- 我想要一个
languages
数组,我可以在其中按language
访问不同的词典:languages[ONE]
- 我想使用字典字段访问不同的翻译表:
languages[ONE].foo
- 所有使用语言+字段对访问的翻译表可能具有不同的数组长度,如代码示例所示
这可能吗?我做错了什么?
当使用 gcc
编译时,我得到了这个(裁剪过的)输出:
asdf.c:27:17: warning: braces around scalar initializer
.foo = {
^
asdf.c:27:17: note: (near initialization for ‘languages[0].foo’)
asdf.c:28:25: warning: braces around scalar initializer
{"LF", A},
^
asdf.c:28:25: note: (near initialization for ‘languages[0].foo’)
asdf.c:28:26: warning: initialization of ‘struct translation *’ from incompatible pointer type ‘char *’ [-Wincompatible-pointer-types]
[...]
代码的多个部分重复相同的警告/注释。
最佳答案
这里有两件事你可以做:
- 为
struct translation *foo;
和struct translation *bar;
分配内存(你也可以使用malloc
来动态分配内存)。例如:
struct dictionary { struct translation foo[10]; struct translation bar[10]; };
- 在您的定义中使用复合文字:
struct dictionary languages[] = { [ONE] = { .foo = (struct translation []){ {"LF", A}, {"LLF", C}, {"RRF", D}, }, .bar = (struct translation []){ {"L", B}, }, }, [ANOTHER] = { .foo = (struct translation []){ {"FF", B}, {"RRF", D}, }, .bar = (struct translation []){ {"LF", B}, {"R", C}, {"RR", D}, }, }, };
注意
如 @M.M 所述,在 struct dictionary
之前添加限定符 const
是一个好主意,如果它的值在运行时不会改变的话。
关于c - 如何初始化这个结构数组的结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53382857/