我正在尝试调整我的数字排序插入排序代码来对字符串输入文件进行排序,例如:
thickness
combed
revocable
escorted
但是,当尝试运行以下命令时,我遇到了段错误(核心转储):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STRING_LEN 80
#define ARRAY_LEN 10000
void insertion_sort(char **a, int n) {
int i;
int j;
char *key;
for (i = 1; i < n; i++) {
key = a[i];
j = i - 1;
while (strcmp(key, a[j]) == -1 && j >= 0) {
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = key;
}
}
void *emalloc(size_t s) {
void *result = malloc(s);
if (NULL == result) {
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}
int main(void) {
int j;
int num_words = 0;
char word[STRING_LEN];
char *wordlist[ARRAY_LEN];
while (num_words < ARRAY_LEN && 1 == scanf("%79s", word)) {
wordlist[num_words] = emalloc((strlen(word) + 1) * sizeof wordlist[0][0]);
strcpy(wordlist[num_words], word);
num_words++;
}
insertion_sort(wordlist, num_words);
for (j = 0; j < num_words; j++) {
printf("%s\n", wordlist[j]);
}
return EXIT_SUCCESS;
}
我发现将 while
条件更改为 > 0
而不是 >= 0
while (strcmp(key, a[j]) == -1 && j > 0)
它对除第一个字符串之外的所有内容进行排序,因为当 j
为 0
并且未进入循环时,输出为:
thickness
combed
escorted
revocable
我是 C 新手,我认为这与访问尚未分配的内存有关,但我很难找到位置。
最佳答案
您的循环测试不正确:
while(strcmp(key,a[j]) == -1 && j>=0){
您应该在使用索引j
之前检查它,并且不应依赖strcmp()
返回-1
对于 key
小于 a[j]
。 strcmp()
仅指定为在这种情况下返回负值。
while (j >= 0 && strcmp(key, a[j]) < 0) {
关于c - 在C中使用插入排序对字符串进行排序 - 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38648965/