计算在给定句子中组成单词的字母

时间:2011-12-30 16:35:47

标签: c c-strings

我正在尝试编写一个程序来查找给定句子中存在多少个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 个答案:

答案 0 :(得分: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标头进行编译。即使它们是标准库的一部分。

答案 1 :(得分: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