在实施this thread中建议的数据结构后,我决定用一些测试值填充它。
代码是
typedef enum {car, gun, bullet} itemtype;
typedef struct bullettype {
unsigned short velocity;
unsigned short kinetic_energy;
} Bullet;
typedef struct cartype {
unsigned short maxspeed;
} Car;
typedef enum {handgun, shotgun, machinegun} weapontype;
typedef struct firearmtype {
weapontype type;
char capacity;
} Firearm;
typedef struct gameitem {
itemtype type;
char* name;
unsigned short bulk;
unsigned short weight;
union {
Car c;
Bullet b;
Firearm f;
};
} Item;
int main() {
Item *objects = malloc(50 *sizeof(Item));
objects[0] = (Item) {gun, "a gun", 500, 5000, (Firearm) {handgun, 10}};
objects[1] = (Item) {car, "a car", 3500, 4000, (Car) {200}};
objects[2] = (Item) {bullet, "a bullet", 200, 3000, (Bullet) {300, 5000}};
free(objects);
return 0;
}
但是当我编译它时,我得到了
itemlisttest.c:40:2: error: incompatible types when initializing type ‘short unsigned int’ using type ‘Firearm’
itemlisttest.c:42:3: error: incompatible types when initializing type ‘short unsigned int’ using type ‘Bullet’
这意味着car
项目正常运行。它在结构中的联合中首先列出。所以我决定像这样在工会中交换Car和Bullet。
union {
Bullet b;
Car c;
Firearm f;
};
现在编译错误
itemlisttest.c:40:2: error: incompatible types when initializing type ‘short unsigned int’ using type ‘Firearm’
itemlisttest.c:41:2: error: incompatible types when initializing type ‘short unsigned int’ using type ‘Car’
这与我初始化结构的方式有关吗?我这样做是因为它将是一个很长的列表,而且1000 object[a].name = "name"
行看起来并不漂亮。
答案 0 :(得分:3)
使用前C99 C,您只能初始化联盟的第一个成员。但是,如果您为工会成员提供名称,则从C99开始,您可以使用指定初始化程序的C99功能:
typedef struct gameitem {
itemtype type;
char* name;
unsigned short bulk;
unsigned short weight;
union {
Car c;
Bullet b;
Firearm f;
}u;
} Item;
objects[0] = (Item) {gun, "a gun", 500, 5000, .u.f=(Firearm) {handgun, 10}};
objects[1] = (Item) {car, "a car", 3500, 4000, .u.c=(Car) {200}};
objects[2] = (Item) {bullet, "a bullet", 200, 3000, .u.b=(Bullet) {300, 5000}};
答案 1 :(得分:1)
您没有为联合字段提供名称:
union {
Bullet b;
Car c;
Firearm f;
} field_name_in_gameitem_struct;