gpt4 book ai didi

c - "incompatible types when initializing type"初始化一个内部有 union 的结构后

转载 作者:行者123 更新时间:2023-12-04 18:22:32 24 4
gpt4 key购买 nike

在实现 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项目工作正常。它在结构内的 union 中首先列出。所以我决定像这样在联盟中交换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"线条看起来一点也不漂亮。

最佳答案

使用 C99 之前的 C,您只能初始化 union 的第一个成员。但是,如果您为 union 成员提供名称,则从 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}};

关于c - "incompatible types when initializing type"初始化一个内部有 union 的结构后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10369034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com