首页 > 解决方案 > 与结构数组不兼容的指针类型

问题描述

我正在尝试编写一个函数,将文件读入结构数组并返回所述数组。当我进行测试运行时,它似乎工作正常(即按预期打印每个条目)。但我不断收到警告:

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;
};

标签: carraysstruct

解决方案


您在函数内部定义结构,这意味着它只能在函数(其主体)范围内使用。因此,您不能将其设为返回类型。

将结构体移出函数体:

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);
    // ...
}

推荐阅读