I've tried so much code trying to display my data in a histogram. I've been stuck on this problem for two days now, data crawling the internet and such to find an answer but they usually talk about pointers and ect. while this is much more basic. I've tried an actual histogram that displayed the same error but for the sake of keeping it simple I choose to post this one.
This is the description of the program from The C Programming language: "Write a program to print a histogram of the lengths of the words in its input. " I'm doing it horizontally then I will do it vertically. Although, in this example I am just trying to display the number, obviously.
#include <stdio.h>
#define MAXIMUM 99
main()
{
int i, c, j, lenOfWord[MAXIMUM], charCount;
for (i = 0; i < MAXIMUM; i++)
lenOfWord[i] = 0;
printf("Starting program, please type then ctrl+d\n");
while((c = getchar()) != EOF) {
if (c == ' ') {
//new word
++lenOfWord[charCount];
charCount = 0;
}
else
//inword
++charCount;
}
printf("\n Displaying now... \n");
for (j = 0; j <= MAXIMUM; j++)
printf("%d: %d", j, lenOfWord[j]);
}
output:
JohnJackson@linux-72db:~/Desktop> gcc c.c -o c
JohnJackson@linux-72db:~/Desktop> ./c
Starting program, please type then ctrl+d
Hello my name is john jacksonSegmentation fault
*Segmentation fault on the end is what i get when I do EOF (ctrl+D)
Additional information: GCC compiler from terminal in openSUSE linux
Thanks so much, I'm trying to learn C but I've hit alot of road blocks like these, I'm getting frustrated.
The actual problem is
++lenOfWord[charCount];
charCount = 0;
You have not initialized charCount
to 0
before using it. Initialize it to 0 first before the loop
charCount = 0;
while((c = getchar()) != EOF) {
And assigning charCount
to 0
in loop is of no use. Remove it.
You have to check one more thing. Since the array size is MAXIMUM
. So You have to put a check that charCount
does not exceed MAXIMUM
. Otherwise, it will again give segmentation fault
.
Another problem is in the for loop condition. Instead of
for (i = 0; i < MAXIMUM; i++)
change it to
for (i = 0; i < MAXIMUM; i++)
And
Instead of
for (j = 0; j >= MAXIMUM; j++)
to
for (j = 0; j < MAXIMUM; j++)
Otherwise you won't get any output.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加