我正在研究 c从 txt
文件中读取并对字符串进行排序的程序。
数据.txt:
jk ef ab cd bc gh fg ij hi de
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
int cmp(const void *p1, const void *p2) {
return strcmp(*(const char **)p1, *(const char **)p2);
}
int main() {
FILE *f = fopen("data.txt", "r");
char s[255][255];
char tmp[255];
int n = 0;
while (!feof(f)) {
fscanf(f, "%s", tmp);
strcpy(s[n], tmp);
n++;
}
fclose(f);
qsort(s, n, sizeof(char *), cmp);
int i = 0;
for (; i < n; i++) {
printf("%s ", s[i]);
}
return EXIT_SUCCESS;
}
我在 Ubuntu 上运行代码,它因段错误而中断。相信这个段错误发生在 qsort
中,我不知道为什么。
谁能给我一些建议?
最佳答案
比较函数不正确,因为你正在对 char
数组的数组进行排序,你可以将指向元素的指针直接传递给 strcmp
:
int cmp(const void *p1, const void *p2) {
return strcmp(p1, p2);
}
但是请注意,您的解析循环也不正确:feof()
不是检查文件结尾的正确方法。改用这个:
n = 0;
while (n < 255 && fscanf(f, "%254s", s[n]) == 1) {
n++;
}
qsort
调用应该指定数组元素的大小:
qsort(s, n, sizeof(*s), cmp);
这是更正后的版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *p1, const void *p2) {
return strcmp(p1, p2);
}
int main(void) {
FILE *f = fopen("data.txt", "r");
char s[255][255];
char tmp[255];
int n = 0;
if (f == NULL)
return EXIT_FAILURE;
while (n < 255 && fscanf(f, "%254s", s[n]) == 1) {
n++;
}
fclose(f);
qsort(s, n, sizeof(*s), cmp);
for (int i = 0; i < n; i++) {
printf("%s ", s[i]);
}
printf("\n");
return EXIT_SUCCESS;
}
关于c - 使用 qsort 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46090062/