Can anyone explain why I am getting segmentation fault in the following example?
#include
#include
int main(void) {
char
A bunch of things wrong:
hello
points to a string literal, which must be treated as immutable. (It could live in read-only memory.) Since strtok_r
mutates its argument string, you can't use hello
with it.
You call strtok_r
only once and don't initialize your tokens
array to point to anything.
Try this:
#include
#include
int main(void) {
char hello[] = "Hello World, Let me live.";
char *p = hello;
char *tokens[50];
int i = 0;
while (i < 50) {
tokens[i] = strtok_r(p, " ,", &p);
if (tokens[i] == NULL) {
break;
}
i++;
}
i = 0;
while (i < 5) {
printf("%s\n", tokens[i++]);
}
return 0;
}