gpt4 book ai didi

c - 当我运行它时出现段错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:13:36 24 4
gpt4 key购买 nike

所以我想创建一个地址簿程序,我有以下代码:

#define MAX_VALUE_FOR_ARRAYS 1000

int i = 0 ;
int answer = 0 ;
int number_of_people = 0 ;

FILE* address_book = NULL ;

address_book = fopen("addressBook.txt", "w") ;

typedef struct People People ;

struct People
{
char f_name[MAX_VALUE_FOR_ARRAYS]
};

People *persons = NULL ;

printf("A D D R R E S S B O O K \n\n\n") ;

printf("1. Add a new contact \n") ;
printf("2. View all contacts \n") ;
printf("\nMake your choice : ") ;

while (answer < 1 || answer > 2)
{
printf("\nWrong input, try again ! : ") ;
scanf("%d", &answer) ;
}

if (answer == 1)
{
printf("How many contacts do you want to add ? : ") ;
scanf("%d", &number_of_people) ;

persons = malloc(number_of_people * sizeof(char*) ) ;

if (persons == NULL)
{
printf("\nMemory allocation failed !") ;
}

for (i = 0; i < number_of_people; i++)
{
printf("Person %d ", (i+1)) ;
printf("Enter the first name : ") ;
scanf("%s", &persons[i].f_name) ;

if (address_book == NULL)
{
printf("\nFailed to open file ! ") ;
}

fputs(persons[i].f_name, address_book) ;
fputc('\n', address_book) ;

}
}

我的问题是,只要变量“number_of_people”大于 3,程序就无法运行(我得到一个段错误),在其他情况下(number_of_people < 3)它可以正常运行。我不知道出了什么问题,请帮忙。

最佳答案

我认为 malloc 调用中存在错误,您分配的指针大小错误。试试这个方法:

    #define MAX_VALUE_FOR_ARRAYS 1000
int i = 0 ;
int answer = 0 ;
int number_of_people = 0 ;

FILE* address_book = NULL ;

address_book = fopen("addressBook.txt", "w") ;

typedef struct People People ;

struct People
{
char f_name[MAX_VALUE_FOR_ARRAYS]
};

People *persons = NULL ;

printf("A D D R R E S S B O O K \n\n\n") ;

printf("1. Add a new contact \n") ;
printf("2. View all contacts \n") ;
printf("\nMake your choice : ") ;


while(1)
{
scanf("%d", &answer) ;
if ( (answer < 1) || (answer > 2) )
printf("\nWrong input, try again ! : ") ;
else
break;
}


if (answer == 1)
{
printf("How many contacts do you want to add ? : ") ;
scanf("%d", &number_of_people) ;

persons = malloc(number_of_people * sizeof(People) ) ;

if (persons == NULL)
{
printf("\nMemory allocation failed !") ;
}

for (i = 0; i < number_of_people; i++)
{
printf("Person %d ", (i+1)) ;
printf("Enter the first name : ") ;
scanf("%s", &persons[i].f_name) ;

if (address_book == NULL)
{
printf("\nFailed to open file ! ") ;
}
fputs(persons[i].f_name, address_book) ;
fputc('\n', address_book) ;

}
}

我还稍微更改了 while 循环,以便仅当用户在第一个菜单中做出错误选择时才显示错误。

关于c - 当我运行它时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54057431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com