繁体   English   中英

C:使用不带 typedef 的结构数组时,“数组类型的元素类型不完整”

[英]C: "array type has incomplete element type" when using array of struct without typedef

问题:以下代码片段编译良好(其中两种结构类型都是类型定义的):

typedef struct {
    int a;
    float b;
} member_struct;

typedef struct {
    int a;
    double b;
    member_struct c;
} outside_struct;

outside_struct my_struct_array[4];

但是,如果“outside_struct”的 typedef 被删除:

typedef struct {
    int a;
    float b;
} member_struct;

struct {
    int a;
    double b;
    member_struct c;
} outside_struct;

struct outside_struct my_struct_array[4];

我收到错误消息: "array type has incomplete element type 'struct outside_struct'". 如果我还删除了“member_struct”的 typedef,我会得到一个额外的错误: "field 'c' has incomplete type"

问题:为什么会发生? 在这里使用 typedef 是绝对必要的吗? 在我的代码中,否则我从不将 typedef 用于结构类型,因此我正在寻找一种方法来避免这种情况,如果可能的话。

在这份声明中

struct {
    int a;
    double b;
    member_struct c;
} outside_struct;

声明了未命名结构类型的 object outside_struct 没有声明名为struct outside_struct的结构。

所以编译器在这个数组声明中发出错误

struct outside_struct my_struct_array[4];

因为在此声明中引入了未定义的类型说明符struct outside_struct 也就是说,在此声明中,类型说明符struct outside_struct是不完整的类型。

您不能声明元素类型不完整的数组。

您需要outside_struct一个与

struct  outside_struct {
    int a;
    double b;
    member_struct c;
};

如果删除 typedef,则需要添加一个结构标记: struct outside_struct {... };

Typedef 用于为另一种数据类型创建附加名称(别名)。

typedef int myInt; //=>equivalent to "int"
myInt index = 0; //=>equivalent to "int index = 0;"

结构的逻辑是一样的。

typedef struct myStruct {} myStruct_t; //=> equivalent to "struct myStruct {};"
myStruct_t myStructVariable; //=> equivalent to "struct myStruct myStructVariable;"

syntaxe = "typedef type newAlias;"

myStruct{} ” 是一种新类型,包含您想要的所有类型(int、char...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM