Я получаю ошибку сегментации при запуске этого - PullRequest
0 голосов
/ 06 января 2019

, поэтому я хочу создать программу адресной книги, и у меня есть следующий код:

#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) она работает правильно. Я не знаю, что происходит, помогите, пожалуйста. </p>

1 Ответ

0 голосов
/ 06 января 2019

Я думаю, что в вызове 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, чтобы показать ошибку, только если пользователь сделал неправильный выбор в первом меню.

...