Problem: The following code snippet compiles well (where both struct types are typedefed):
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];
However, if the typedef of the "outside_struct" is dropped:
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];
I get the error:
"array type has incomplete element type 'struct outside_struct'".
And if I also drop the typedef of "member_struct", I get an extra error:
"field 'c' has incomplete type"
Question: Why it happens? Is using typedef strictly necessary here? In my code, I otherwise never use typedef for structure types, so I am looking for a way to avoid that, if possible.
CodePudding user response:
In this declaration
struct {
int a;
double b;
member_struct c;
} outside_struct;
there is declared the object outside_struct
of unnamed structure type. Neither structure with the name struct outside_struct
is declared.
So the compiler issues an error in this declaration of an array
struct outside_struct my_struct_array[4];
because in this declaration there is introduced the type specifier struct outside_struct
that is not defined. That is in this declaration the type specifier struct outside_struct
is an incomplete type.
You may not declare an array with an incomplete element type.
Instead of declaring the object outside_struct
of an unnamed structure you need to declare a structure with the same tag name as
struct outside_struct {
int a;
double b;
member_struct c;
};
CodePudding user response:
If you drop the typedef, you need to add a struct tag instead: struct outside_struct { ... };
CodePudding user response:
Typedef is used to create an additional name (alias) for another data type.
typedef int myInt; //=>equivalent to "int"
myInt index = 0; //=>equivalent to "int index = 0;"
It's the same logic for struct.
typedef struct myStruct {} myStruct_t; //=> equivalent to "struct myStruct {};"
myStruct_t myStructVariable; //=> equivalent to "struct myStruct myStructVariable;"
syntaxe = "typedef type newAlias;"
"myStruct{}" is a new type that contain all the type that you want (int, char...)