1
我试着去适应我的电话号码的排序插入排序代码排序如字符串输入文件来代替:排序字符串在C插入排序 - 分段错误
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
它排序的一切,但第一个字符串,因为这是当j
是0
并没有进入循环,输出为:
thickness
combed
escorted
revocable
我是新的C和我收集这是与访问尚未分配的内存有关,但我正在努力查看在哪里。
你今天打在所有的8缸! –
@ DavidC.Rankin:拖延一些更重要的工作是如此令人难以置信的有效动机';-)' – chqrlie
@yhsdygdyusgdysgdsudsd:请点击答案分数下面的灰色复选标记,接受答案吗? – chqrlie