I'm not too sure why this code causes segfault. I'm trying to find out how many words does a sentence contain. Can anyone help me resolve this?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 1000
int main(void){
char sentence[MAX + 1] = {0};
char *word;
int count, len, i, num = 0;
while(fgets(sentence, MAX, stdin)){
num = 0;
word = sentence;
word = strtok(word, " ");
while(sentence != NULL){
char separate[MAX + 1] = {0};
count = 0;
word = strtok(NULL, " ");
strcpy(separate, word);
len = strlen(separate);
for(i = 0; i < len; i++)
if(isalpha(sentence[i]))
count++;
if(count == len || count == len - 1)
num++;
}
printf("%d\n", num);
}
return 0;
}