在c中排序字符串数组,但程序崩溃

时间:2018-04-12 17:52:17

标签: c

我循环浏览文件以查找用户输入的匹配记录,然后我需要按升序打印它们。我的程序一直在崩溃。我需要帮助。我写了一些函数来完成这项工作。

static int myCompare (const void * a, const void * b)
{
    return strcmp (*(const char **) a, *(const char **) b);
}

void sort(const char *arr[], int n)
{
    qsort (arr, n, sizeof (const char *), myCompare);
}

void search_contact() {
    FILE * fp;
    bool found = false;
    char *records;
    fp = fopen("contact.txt", "r");
    system("cls");
    printf("\t*****SEARCH CONTACT*****");
    printf("\n\t Enter Mobile: ");
    char mobile[20];
    scanf("%s", mobile);
    char mobile1[20], name[20];    
    while (fscanf(fp, "%s %s", name, mobile1) != EOF) {
        if (strcmp(mobile, mobile1) == 0) {
            records = malloc(sizeof(name));
            strcpy(records,name);

            int i;
        //  printf(" %s", records);
            found = true;
        } else {
            found = false;
        }
    }
    if(found){
        int n = sizeof(records)/sizeof(records[0]);
         sort(records, n);
         int i;
         for (i = 0; i < n; i++)
            printf("%s \n", records[i]);
    }
    else{
        printf("\n No Records Found!");
    }
    fclose(fp);
    printf("\n\tPRESS ANY KEY TO CONTINUE");
    getch();
    main();
}

1 个答案:

答案 0 :(得分:1)

您希望records成为字符串数组,因此它应该是:

char **records = NULL;
int num_records = 0;

然后,当您将一个字符串添加到记录数组时:

records = realloc(records, sizeof(*records) * (num_records + 1));
if (NULL == records) { // Handle failure }
records[num_records] = malloc(strlen(name) + 1);
if (NULL == records[num_records]) { // Handle failure }
strcpy(records[num_records], name);
num_records += 1;

不要忘记free()所有数据。