我正在尝试编写一个将文件读入结构数组并返回所述数组的函数。当我进行测试运行时,它似乎工作正常(即按预期方式打印每个条目)。但我不断收到警告:
main.c:53:16: warning: incompatible pointer types returning 'struct Vehicles *' from a
function with result type 'struct Vehicles *' [-Wincompatible-pointer-types]
return inventory;
哪个听起来有点可笑,是因为struct Vehicles *
与struct Vehicles *
不兼容?谁能帮助我理解为什么我收到此警告,并可能提供有关如何适当地返回结构数组的更多见解?
我正在测试的“ hw2.data”文件只有三个条目(但是我们的讲师将测试100个条目),看起来像这样:
F150 5.4 28000 white
RAM1500 5.7 32000 orange
TOYOTA 2.1 16000 red
我的函数(到目前为止)如下所示:
struct Vehicles *readFile(char file_name[16]) {
struct Vehicles {
char vehicle[16];
float engine;
int price;
char color[16];
};
struct Vehicles *inventory = malloc(sizeof(struct Vehicles)*100);
FILE *input;
char vehicle[16];
float engine;
int price;
char color[16];
int count = 0;
//struct Vehicles inventory[3];
input = fopen(file_name, "r");
while (fscanf(input, "%s %f %d %s", vehicle, &engine, &price, color) == 4) {
strcpy(inventory[count].vehicle, vehicle);
strcpy(inventory[count].color,color);
inventory[count].engine = engine;
inventory[count].price = price;
printf("%s %.2f %d %s\n", inventory[count].vehicle, inventory[count].engine, inventory[count].price, inventory[count].color);
count++;
}
fclose(input);
return inventory;
}
int main(void) {
readFile("hw2.data");
return 0;
};
答案 0 :(得分:1)
您可以在函数内部定义结构,这意味着它只能在函数范围内(其主体)使用。因此,您不能使其成为返回类型。
将结构移出函数主体:
struct Vehicles {
char vehicle[16];
float engine;
int price;
char color[16];
};
struct Vehicles *readFile(char file_name[16]) {
struct Vehicles *inventory = malloc(sizeof(struct Vehicles)*100);
// ...
}
答案 1 :(得分:1)
根据C 2018 6.7.2.3 5,两个在不同作用域中的结构声明声明不同的类型:“两个在不同作用域或使用不同标签的结构,联合或枚举类型的声明声明不同的类型。” >
在struct Vehicles *readFile(char file_name[16]) {…
中,结构声明位于文件范围内。
函数struct Vehicles {…
中的声明位于块范围内。
因此,struct Vehicles
的这两种用法,即使它们使用相同的标签,也指的是不同的类型。