I want to find length of word from string. When i use strlen(split) out of while loop it's ok. But when i use it from loop i have segmentation fault error. What's the problem?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char string[] = "Hello world!";
char* word = strtok(string, " ");
printf("%d\n", strlen(word));
while(split != NULL) {
word = strtok(NULL, " ");
printf("%d\n", strlen(word ));
}
}
You need to check that strtok didn't return NULL before calling strlen
From the strtok man page (my emphasis)
Each call to strtok() returns a pointer to a null-terminated string containing the next token. This string does not include the delimiting byte. If no more tokens are found, strtok() returns NULL.
while(word != NULL) {
word = strtok(NULL, " ");
if (word != NULL) {
printf("%d\n", strlen(word ));
}
}
Note that there was also a typo in your code. The while loop should test word rather than split.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With