【发布时间】: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 书是唯一的答案。我