2016-07-29 84 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