My code looks like this
struct {
int valid;
int pid;
int heading;
int speed;
} car;
struct car road[10]; //a road filled with cars
However, my compiler is complaining:
"incomplete struct/union/enum car: road"
What am I doing wrong? I looked at examples online and they show that this is how to initialize arrays of structs.
If it isn't obvious, I'm trying to make an array of car structs
Change :
struct {
int valid;
int pid;
int heading;
int speed;
} car;
which declares only one instance of an unnamed structure , with the name car
, to :
struct car{
int valid;
int pid;
int heading;
int speed;
};
which declares a new type struct car
.The struct
's name needs to be next to the keyword struct
.
You can also do :
typedef struct {
int valid;
int pid;
int heading;
int speed;
} car;
and then you only refer to this struct
as car
, not struct car
.
See this link for more information on structs
and their syntax.
This:
struct {
...
} car;
declares a single instance of an anonymous structure, called car
. You can view the struct {... }
part as analogous with any other type name, except a new type is used. Since you don't give the structure a name, you can't create more than the car
instance.
This might seem like a pointless thing to do, but it can be really useful when you want to group things together.
What you meant was this:
struct car {
...
};
which declares a new struct type, called struct car
. You can use this name to refer to the declaration, and eg later create a bunch of instances like you did:
struct car road[10];
Option 1 (without typedef):
struct car {
int valid;
int pid;
int heading;
int speed;
};
struct car road[10];
Option 2 (with typedef with unnamed struct):
typedef struct {
int valid;
int pid;
int heading;
int speed;
} car_t;
car_t road[10];
Option 3 (with typedef with named struct):
typedef struct car {
int valid;
int pid;
int heading;
int speed;
} car_t;
car_t road[10];
//or
struct car road[10];
The Linux Coding Style states:
It's a mistake to use typedef for structures...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.