簡體   English   中英

在結構中使用帶有浮點變量的 malloc

[英]using malloc with a float variable in struct

對於我的 class,我們正在練習使用 malloc 和 memcpy 將輸入輸入到組成數據庫的struct中。 在哪里輸入浮點數和兩個單獨的字符。 我在這里遇到的問題是,當我嘗試將malloc用於浮點輸入時,它給了我一個錯誤,指出a value of type "float*" cannot be assigned to an entity of type "float" 在我的結構聲明中,我將它聲明為float price ,但我遇到的問題是,如果我將其更改為float price* ,我用來預填充結構錯誤的變量說a value of type "double" cannot be used to initialize an entity of type "float*"

我也試過做malloc(sizeof(price)); 只是本身沒有浮動演員,但這似乎也沒有讓我到任何地方

關於指針的工作方式,我是否遺漏了什么? 他們是帶有浮點變量的malloc的正確方法還是自動完成?

void getInfo(struct movieRental *temp){


float price;
printf("Please type in a price ");
scanf("%f", &price);
temp->price = (float* ) malloc(sizeof(price));
memcpy(temp->price, &price, sizeof(price));
}

struct movieRental{

char *title;
char *director;
float price; //changing this to "float *price" errors out my prefilled structs for a later function
};


struct movieRental rental1 = { 
    "Indiana Jones and the last Crusade",
    "Steven Spielberg", 
    12.55,

};


struct movieRental rental2 = {
    "Star Wars Episode 4",
    "George Lucas",
    24.75,


};



struct movieRental rental3 = {
    "Office Space",
    "Mike Judge",
    45.50,
};

您誤解了應該如何分配 memory。 price成員是movieRental結構的一部分。 您不需要在此處分配 memory,因為getInfo function 已經收到指向movieRental結構的指針,因此它不是 ZC1C425268E68385D14AB5074C17A9 的責任。

相反,您可以將數據直接讀入結構成員:

scanf("%f", &temp->price);

我建議選擇比temp更好的變量名。

您在結構中有float price 您不需要也不應該嘗試為價格分配 memory。 只需將值存儲在變量中。 理論上,您可以在結構中使用float *price ,然后您需要為變量分配 memory ,但這樣做毫無意義,會不必要地使用空間。

在大多數系統上, sizeof(float) == 4 如果您使用的是 32 位系統,則float的大小將與float *相同,因此您會產生不必要的指針的 memory 開銷和更復雜的代碼來訪問價格(訪問會更慢)。 如果您使用的是 64 位系統,則指針的大小是float的兩倍,而浪費也大得多。 還有與每個 memory 分配相關的開銷。

您的 function 可能是:

void getInfo(struct movieRental *temp){
    printf("Please type in a price ");
    if (scanf("%f", &temp->price) != 1)
    {
        …handle error…but how?
    }
}

您可以讀入一個局部變量,然后簡單地將局部變量分配給結構元素,但實際上並不需要。 對於錯誤處理,最好將 function 返回類型更改為int (或bool ),以便指示成功或失敗。 您可能還應該重命名 function; 它得到價格,與“價格”相比,“信息”是一個模糊的術語。

int getPrice(struct movieRental *temp){
    float price;
    printf("Please type in a price ");
    if (scanf("%f", &temp->price) != 1)
        return -1;
    return 0;
}

暫無
暫無

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

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