【问题标题】:Error incompatible types when initializing type 'enum Zahlen' using type 'struct s_action (*)使用类型“struct s_action (*)”初始化类型“enum Zahlen”时出错类型不兼容
【发布时间】: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 使用了正确的类型,它就可以工作。

标签: c gcc struct enums


【解决方案1】:

struct s_testschritt 中的字段actions 是一个灵活的数组成员。您不能将数组(或指向数组的指针)分配给它。

您想要将此成员声明为指针。然后使用数组myactions 对其进行初始化,该数组将衰减为指向第一个元素的指针。

struct s_testschritt{
    int actioncount;
    struct s_action *actions;
};

struct s_action myactions[20];

struct s_testschritt aTestschritt = {
    .actioncount = 20,
    .actions = myactions

};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    相关资源
    最近更新 更多