【发布时间】:2019-10-17 13:13:45
【问题描述】:
谁能告诉我为什么我的代码不起作用? 它可以正确编译,但在执行过程中,它会停止给出错误消息。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct book
{
char cName[100];
float fPrice;
};
struct book *ptr;
void display(int j)
{
int i=0;
ptr = ptr - j;
while(i<j)
{
printf("Book name: %s\n",ptr->cName);
printf("Price: %f\n\n",ptr->fPrice);
ptr++;
i++;
}
}
int main()
{
int i,n;
printf("How many entries do you want to make: ");
scanf("%d",&n);
ptr = (struct book*)malloc(n*sizeof(struct book));
for(i=0;i<n;i++)
{
printf("Enter the Name: ");
scanf("%s",ptr->cName);
printf("Enter price: ");
scanf("%f",ptr->fPrice);
ptr++;
}
display(n);
return 0;
}
免责声明:我是 C 的新手,如果我的编码伤害了你的眼睛,我真诚地提前道歉。只是想了解程序而不是快速完成它。
【问题讨论】:
-
scanf("%f",ptr->fPrice);行应该是scanf("%f",&ptr->fPrice);函数scanf需要变量的地址。在前一行中,数组 decays 指向一个指针,因此不需要&。 -
不要修改
ptr——你需要保留malloc()返回的值,以便以后可以释放内存。在main()和display()中都使用ptr[i](或ptr[i].cName等)。最好将ptr和n传递给display()— 尽可能避免使用全局变量。 (如所写,您需要在main()中写入free(ptr - n)以发布数据。这不是惯用的C。)此外,您可以(应该)是系统的;你在main()中使用for循环,在display()中没有理由不这样做。 -
...虽然你说它编译正确,但有一个编译器警告。