подсчет букв, составляющих слова в данном предложении - PullRequest
2 голосов
/ 30 декабря 2011

Я пытаюсь написать программу, чтобы узнать, сколько слов в одном предложении, двух, трех, четырех букв существует в данном предложении, и я наконец-то нашел код. Тем не менее, есть проблема. Код был успешно скомпилирован, но когда он запускается, программа завершается сбоем и завершается безрезультатно.

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 ]

2 голосов
/ 30 декабря 2011

Вы 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 голосов
/ 30 декабря 2011
#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 
...