【发布时间】:2017-01-31 19:57:55
【问题描述】:
我在用 C 定义结构时遇到了问题。我使用 GCC。 代码如下:
#include <stdio.h>
#include <stdlib.h>
typedef enum Zahlen {
eins =0,
zwei,
drei
}tZahlen;
struct s_action{
tZahlen aZahl;
void *argument;
char name[];
};
struct s_testschritt{
int actioncount;
struct s_action actions[];
};
struct s_action myactions[20];
struct s_testschritt aTestschritt = {
.actioncount = 20,
.actions = &myactions
};
int main(int argc, char *argv[]) {
return 0;
}
这在编译时给了我以下错误:
[Error] incompatible types when initializing type 'enum Zahlen' using type 'struct s_action (*)[20]'
当我在 struct s_action 中省略枚举 Zahlen 时,一切正常。但我在我的 struct s_action 中需要这个枚举。
如何正确定义和初始化?
【问题讨论】:
-
问题出在
actions字段中。您不能分配一个数组成员。使用指针或memcpy。 -
dbush 的回答应该消除警告。但它仍然存在
s_action结构还包含一个灵活的数组成员的问题,并且没有为它分配存储空间。当结构具有灵活的数组成员时,例如char name[],您不能声明这些结构的数组,例如struct s_action myactions[20]。该数组声明不会为name成员保留任何空间。 -
@JakubKaszycki:这不是赋值,而是初始化程序。如果 OP 使用了正确的类型,它就可以工作。