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 
4

2 回答 2

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即使它们是标准库的一部分。

于 2011-12-30T16:41:13.993 回答
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 
于 2011-12-30T18:10:43.350 回答