运行此程序时出现细分错误

时间:2019-01-05 23:58:09

标签: c arrays pointers dynamic-memory-allocation

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

#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),程序就可以正常工作。我不知道怎么了,请帮忙。

1 个答案:

答案 0 :(得分:2)

我认为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循环,仅当用户在第一个菜单中选择错误时才显示错误。

相关问题