2015-02-05 42 views
-1

程序分離文件並逐個打印文字,但是當我編譯並運行它時,它表示分段錯誤。字計數器中的分段錯誤

main

部分:

char * w; 
int Counter = 0; 
while ((w = nextword(fd)) != NULL) { 
    printf("%d: %s\n", Counter, w); 
    Counter++; 
} 
printf("words total = %d\n", Counter); 

功能nextword

char * nextword(FILE * fd) { 
int c; 
int i; 
c = fgetc(fd); 
while (c != -1) { 
    while ((c != ' ') && (c != '\n')) { 
     word[wordLength] = c; 
     wordLength++; 
    } 
    return word; 
    wordLength = 0; 
} 
+0

凡'wordLength'聲明?它的價值是什麼? – Axalo 2015-02-05 17:16:09

回答

0

儘量把

return word; 

wordLength=0; 

我的猜測是,你永遠不會重置你的wordLength,而你最終會讓wordLenght變得非常高。

另請注意,使用全局緩衝區/計數器不是一個好習慣。

+0

我試過把wordLength = 0;在退貨聲明之前,仍然存在分段錯誤... – post5858 2015-02-05 17:11:09

1

這是什麼原因造成的問題:

return word; 
wordLength = 0; 

一旦你回來,永遠達不到wordLength = 0;聲明。

將其移至函數的頂部以修復您的實現。

更好的實現將使用臨時緩衝區,而不是全局的緩衝區。例如,你可以這樣做:

size_t nextword(FILE * fd, char buf[], size_t max_len) { 
    size_t len = 0; 
    ... // Read data into buf up to max_len-1. 
     // Then add null terminator, and return length. 
     // When you return length of zero, it means the end of input 
    return len; 
} 

主叫方會調用你的函數是這樣的:

char w[100]; 
while (nextword(fd, w, 100) != 0) { 
    printf("%d: %s\n", Counter, w); 
    Counter++; 
}