【问题标题】:using malloc with a float variable in struct在结构中使用带有浮点变量的malloc
【发布时间】:2021-02-13 23:20:13
【问题描述】:

在我的课堂上,我们正在练习使用 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,
};

【问题讨论】:

  • @JonathanLeffler 我认为一本 C 书是唯一的答案。我

标签: c pointers malloc


【解决方案1】:

您误解了应该如何分配内存。 price 成员是 movieRental 结构的一部分。你不需要在这里分配内存,因为getInfo 函数已经接收到一个指向movieRental 结构的指针,所以它不是函数的责任。

相反,您可以将数据直接读入结构成员:

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

我建议选择比 temp 更好的变量名。

【讨论】:

    【解决方案2】:

    结构中有float price;您不需要也不应该尝试为价格分配内存。只需将值存储在变量中。理论上,您可以在结构中使用float *price,然后您需要为变量分配内存,但这样做是没有意义的,会不必要地使用空间。

    在大多数系统上,sizeof(float) == 4。如果您使用的是 32 位系统,float 的大小将与 float * 相同,因此您会产生不必要的指针和更复杂的代码来访问价格的内存开销(访问将是慢点)。如果您使用的是 64 位系统,则指针是 float 的两倍大,而且浪费要大得多。还有与每个内存分配相关的开销。

    你的功能可能是:

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

    您可以读入一个局部变量,然后简单地将局部变量分配给结构元素,但实际上并不需要。对于错误处理,最好将函数返回类型更改为int(或bool),以便指示成功或失败。您可能还应该重命名该函数;它得到价格,与“价格”相比,“信息”是一个模糊的术语。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      相关资源
      最近更新 更多