c - 与结构数组不兼容的指针类型
问题描述
我正在尝试编写一个函数,将文件读入结构数组并返回所述数组。当我进行测试运行时,它似乎工作正常(即按预期打印每个条目)。但我不断收到警告:
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;
};
解决方案
您在函数内部定义结构,这意味着它只能在函数(其主体)范围内使用。因此,您不能将其设为返回类型。
将结构体移出函数体:
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);
// ...
}
推荐阅读
- docker - docker:如何在 shell 入口点“sh -c”中使用 shell 变量?
- javascript - 将 props 传递给实现 react suspense 的 axios hook
- python - 队列空方法是否损坏?
- python - 使用 Tensorflow Keras 在 CPU 上并行训练 N 个网络
- python - 将 PYTHONPATH 添加到 .zprofile/.bash_profile
- python-3.x - 从单个列表生成多个列表
- flutter - 如何在 Visual Code 上定位 Flutter 和 Dart?
- apache-kafka - AggregationStrategy with org.apache.camel.CamelExchangeException:相关键无效
- c++ - 重新分配 std::unique_ptr 时是否释放内存?
- cmake - 如何在 ubuntu 20.04 中从源代码构建 Aseprite?CMake 警告:“未提供源或二进制目录”