0 c printf pointers scanf dynamic-memory-allocation
插入所有值后,我期望最终的 printf 语句给出方程的最终结果
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *carModel;
float tankRange;
float gasCost;
float costTank;
float gallonsTank; //gallons in full tank
float mpg; //miles per gallon
float costMile;
carModel = malloc(256);
printf("What is the model of car? " );
scanf("%255s", &carModel); // Don't read more than 255 chars
printf("How many miles can be driven on a full tank? " );
scanf("%f", &tankRange);
printf("What is the gas cost per gallon? " );
scanf("%f", &gasCost);
printf("How much does it cost to fill the tank? " );
scanf("%f", &costTank);
gallonsTank = costTank / gasCost;
mpg = tankRange / gallonsTank;
costMile = mpg / gasCost;
printf("Amazing! %255s has an mpg of %.3f per gallon! You spent $%.2f to drive one mile!\n", carModel, mpg, costMile);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
除了最后一个 printf 语句外,所有内容都打印并运行良好,这表明代码已完成运行
scanf的这个调用是不正确的
printf("What is the model of car? " );
scanf("%255s", &carModel); // Don't read more than 255 chars
^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
相反你必须写
printf("What is the model of car? " );
scanf("%255s", carModel); // Don't read more than 255 chars
Run Code Online (Sandbox Code Playgroud)
否则调用会scanf覆盖局部变量占用的内存。
s当您传递类型的参数时,转换说明符需要char *一个 类型的参数char **。
如果你想输入一个包含多个单词的字符串,那么你可以这样写
printf("What is the model of car? " );
scanf("%255[^\n]", carModel); // Don't read more than 255 chars
Run Code Online (Sandbox Code Playgroud)
请注意,应在程序结束时释放分配的内存
free( carModel );
Run Code Online (Sandbox Code Playgroud)