gpt4 book ai didi

c - 在c中对字符串数组进行排序,但程序崩溃

转载 作者:行者123 更新时间:2023-11-30 21:22:55 25 4
gpt4 key购买 nike

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

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();
}

最佳答案

您希望 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()所有这些数据。

关于c - 在c中对字符串数组进行排序,但程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49803044/

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