2011-12-30 70 views
2

我正在編寫一個程序來查找給定句子中存在多少個單字母,雙字母,三字母,四個字母的單詞,並且我終於拿出一些代碼。但是,有一個問題。代碼已成功編譯,但是在運行時,程序將失敗並退出,結果不會發生。計算給定句子中構成單詞的字母

int main(void) 
{ 
char *sentence = "aaaa bb ccc dddd eee"; 
int word[ 5 ] = { 0 }; 
int i, total = 0; 

// scanning sentence 
for(i = 0; *(sentence + i) != '\0'; i++){ 
    total = 0; 

    // counting letters in the current word 
    for(; *(sentence + i) != ' '; i++){ 
     total++; 
    } // end inner for 

    // update the current array 
    word[ total ]++; 
} // end outer for 

// display results 
for(i = 1; i < 5; i++){ 
    printf("%d-letter: %d\n", i, word[ i ]); 
} 

system("PAUSE"); 
return 0; 
} // end main 

回答

2

您在最後一個詞之後進行了分割。內循環在到達空終止符時不終止。

$ gcc -g -o count count.c 
$ gdb count 
GNU gdb (GDB) 7.3-debian 
Copyright (C) 2011 Free Software Foundation, Inc. 
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> 
This is free software: you are free to change and redistribute it. 
There is NO WARRANTY, to the extent permitted by law. Type "show copying" 
and "show warranty" for details. 
This GDB was configured as "x86_64-linux-gnu". 
For bug reporting instructions, please see: 
<http://www.gnu.org/software/gdb/bugs/>... 
Reading symbols from /home/nathan/c/count...done. 
(gdb) run 
Starting program: /home/nathan/c/count 

Program received signal SIGSEGV, Segmentation fault. 
0x00000000004005ae in main() at count.c:9 
9  for(i = 0; *(sentence + i) != '\0'; i++){ 
(gdb) p i 
$1 = 772 

其他評論:爲什麼在最後撥打system("PAUSE")?確保您使用的庫爲-Wall#include頭文件進行編譯。即使它們是標準庫的一部分。

0
#include <stdio.h> 

int main(void){ 
    char *sentence = "aaaa bb ccc dddd eee"; 
    int word[ 5 ] = { 0 }; 
    int i, total = 0; 

    // scanning sentence 
    for(i = 0; *(sentence + i) != '\0'; i++){ 
     total = 0; 

     // counting letters in the current word 
     for(; *(sentence + i) != ' '; i++){ 
      if(*(sentence + i) == '\0'){ 
       --i; 
       break; 
      } 
      total++; 
     } // end inner for 

     // update the current array 
     word[ total-1 ]++; 
    } // end outer for 

    // display results 
    for(i = 0; i < 5; i++){ 
     printf("%d-letter: %d\n", i+1, word[ i ]); 
    } 

    system("PAUSE"); 
    return 0; 
} // end main