I am trying to write a program to find how many 1-letter, 2-letter, 3-letter, 4-letter words exist in a given sentence, and I have finally come up with some code. However, there is a problem. The code has been successfully compiled, but when it comes to running, the program fails and quits with no result.
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
You’re segfaulting after the last word. The inner loop doesn’t terminate when it gets to the null terminator.
Other comments: Why call
system("PAUSE")at the end? Make sure you compile with-Walland#includeheaders for the libraries you use. Even if they’re part of the standard library.