このスレッドで提案されているデータ構造を実装した後、いくつかのテスト値を入力することにしました。
コードは
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
アイテムが正常に機能していることを意味します。そして、それは構造体内のユニオンの最初にリストされています。だから私はこのように組合で車と弾丸を交換することにしました
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’
これは、構造体を初期化する方法と関係がありますか?object[a].name = "name"
それは長いリストになり、1000行はまったくきれいに見えないので、私はそのようにしています。