这是我的代码。
#include <stdio.h>
struct book
{
char title[30];
char author[30];
char isbn[30];
float price;
}books[5];
int main()
{
int i=1,j=0;
while(i<6)
{
printf("Enter Title of Book No %d : ",i);
scanf("%[^\n]s",&books[j].title);
printf("Enter Author of Book No %d : ",i);
gets("%s",books[j].author);
i++;
j++;
}
printf("%s",books[3].author);
}
我在运行程序时不断出现分段错误。有什么解决办法吗?
我首先使用 gets,然后尝试使用 Scanf 而不是 gets。我还尝试在主函数中声明结构变量。
这是我遇到的错误
└─$ ./a.out
Enter Title of Book No 1 : ttn ttr
zsh: segmentation fault ./a.out
首先,gets 只接受一个参数。
其次,scanf一个字符串时,不需要加&
以下修改在我的设备中运行良好。
#include <stdio.h>
typedef struct book
{
char title[30];
char author[30];
char isbn[30];
float price;
}book;
book books[5];
int main()
{
int i=0,j=0;
while(i<5)
{
printf("Enter Title of Book No %d : ",i);
scanf("%[^\n]s", books[j].title);
printf("Enter Author of Book No %d : ",i);
gets(books[j].author);
i++;
j++;
}
printf("%s",books[3].author);
}