Question

FIXED: Hey I am getting this strange Segmentation Fault in C when I am trying to count the words in a text. Can anyone explain me why and a solution for the seg-fault?

Here is my source code:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>

int isword(char *str) {
    return (isalnum(*(str + 1))) ? 1 : 0;
}

int main() {
    char **text, c;
    int n, i, j;

    //reading from stdin & allocating it dynamically
    scanf("%d\n", &n);
    text = malloc(n * sizeof(char *));
    for(i = 0; i < n; i++) {
        text[i] = malloc(200 * sizeof(char));
    }

    for(i = 0; i < n; i++) {
        for(j = 0; ; j++) {
            scanf("%c", &c);
            if(c == '\n') {
                break;
            }
            text[i][j] = c;
        }
    }

    // Counting words
    int word_counter = 0;
    char *delimitor = " ";
    char *pos;
    for(i = 0; i < n; i++) {
        pos = text[i];
        do {
            if(isspace(*pos) && isword(pos)) {
                word_counter++;
            }
            pos ? pos++ : pos;
            // pos++;
        } while(*pos != '\0');
    }

    printf("Number of words: %d\n", word_counter);
    return 0;
}

Example of input:

4
Adam baked a pie.
Mary   went         to a movie
Mark goes like ?? him
Gina is, hot

Please notice the excessive uses of spaces in the second sentence.

I also have another question about my reading from stdin. Is there a better way to achieve this? I mean I tried to do it with fgets, but I failed, and I know I am not supposed to use gets (hell, even GCC gives it as a warning if you use gets).

Another question: Why doesn't it print the expected number of words? And it prints 12 instead of 14?

Was it helpful?

Solution

    pos ? pos++ : pos;
    // pos++;
} while(pos != '\0');

to

    *pos ? pos++ : pos;
    // pos++;
} while(*pos != '\0');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top