2011-12-30 4 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입니다. 내부 루프는 널 종결자가 될 때 종료되지 않습니다.

$ 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 
관련 문제