2016-07-29 53 views
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

发现

它排序的一切,但第一个字符串,因为这是当j0并没有进入循环,输出为:

thickness 
combed 
escorted 
revocable 

我是新的C和我收集这是与访问尚未分配的内存有关,但我正在努力查看在哪里。

回答

3

你的循环测试是不正确的:

while(strcmp(key,a[j]) == -1 && j>=0){ 

你应该使用它检查索引j以前,你不应该超过a[j]key依靠strcmp()返回-1strcmp()仅被指定为返回此情况的负值。

while (j >= 0 && strcmp(key, a[j]) < 0) { 
+0

你今天打在所有的8缸! –

+0

@ DavidC.Rankin:拖延一些更重要的工作是如此令人难以置信的有效动机';-)' – chqrlie

+0

@yhsdygdyusgdysgdsudsd:请点击答案分数下面的灰色复选标记,接受答案吗? – chqrlie