【发布时间】:2018-02-15 19:42:04
【问题描述】:
我正在开发一个c 程序来读取txt 文件并对字符串进行排序。
data.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,我不知道为什么。
谁能给我一些建议?
【问题讨论】:
-
1)
sizeof(char *)-->sizeof(*s) -
2)
return strcmp( *(const char **) p1, *(const char **) p2);-->return strcmp( (const char *) p1, (const char *) p2); -
编译所有警告和调试信息(例如
gcc -Wall -Wextra -g和GCC....)然后使用调试器(例如gdb)。仔细阅读qsort(3) 的文档。使用C dynamic memory allocation -
@BLUEPIXY: Re 2.: 你确定吗?
标签: c c segmentation-fault qsort