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项目工作正常。它在结构内的联合中首先列出。所以我决定像这样在联盟中交换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’

这与我初始化结构的方式有关吗?我这样做是因为这将是一个很长的列表,而且 1000object[a].name = "name"行看起来一点也不漂亮。

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 回答