簡體   English   中英

與結構數組不兼容的指針類型

[英]Incompatible pointer types with array of structs

我正在嘗試編寫一個函數,將文件讀入結構數組並返回所述數組。 當我進行測試運行時,它似乎工作正常(即按預期打印每個條目)。 但我不斷收到警告:

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

根據 C 2018 6.7.2.3 5:“在不同范圍內或使用不同標簽的結構、聯合或枚舉類型的兩個聲明聲明不同的類型。”

struct Vehicles *readFile(char file_name[16]) {… ,結構聲明在文件范圍內。

函數內的聲明struct Vehicles {…位於塊范圍內。

因此,這兩種struct Vehicles用法,即使使用相同的標簽,也指代不同的類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM