如何避免这种结构分段错误

问题描述 投票:0回答:1

这是我的代码。

#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
                                     
c segmentation-fault scanf structure gets
1个回答
0
投票

首先,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);


}
© www.soinside.com 2019 - 2024. All rights reserved.