2011-12-30 17 views
2

1文字、2文字、3文字、4文字の単語がいくつあるかを特定するプログラムを作成しようとしています。いくつかのコードを思いついてください。しかし、問題があります。コードは正常にコンパイルされましたが、実行するとプログラムは失敗し、結果がなくなります。与えられた文章中の単語を構成する文字を数える

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

最後の単語の後にsegfaultingしています。内部ループは、NULLターミネータに到達すると終了しません。

$ 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 
関連する問題