2

このスレッドで提案されているデータ構造を実装した後、いくつかのテスト値を入力することにしました。

コードは

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行はまったくきれいに見えないので、私はそのようにしています。

4

2 に答える 2

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}};
于 2012-04-29T01:56:33.057 に答える
1

ユニオンフィールドの名前を指定しませんでした:

union {
    Bullet b;
    Car c;
    Firearm f;
} field_name_in_gameitem_struct;
于 2012-04-29T01:49:27.990 に答える