strcpy causing segfault while using strtok -
i'm not sure why code causes segfault. i'm trying find out how many words sentence contain. can 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; < len; i++) if(isalpha(sentence[i])) count++; if(count == len || count == len - 1) num++; } printf("%d\n", num); } homecoming 0; }
you didn't check whether word
null before called strcpy
on it.
also, loop condition, sentence != null
, never false. sentence
isn't reassigned null. perhaps should testing word != null
?
strtok strcpy
No comments:
Post a Comment