string - Why I need to use NULL pointer when using strtok() in C? -


first code:

#include <stdio.h> #include <string.h>  int main() {     char str[100]="nahin bin kaysar";     char *space;      space = strtok(str," ");     while(space != null) {         space = strtok(null," ");         puts(space);     }     return 0; } 

i know program split string 3 different parts. before loop split first word , assigned string space. question why had usenull pointer inside loop parameter of strtok() function. have searched hours , no answer satisfied needs.

first of all, should read again docs , make sure understand each parameter , return.

second, code broken, @ point puts use null argument , it'll crash, fix this:

#include <string.h> #include <stdio.h>  int main() {     char str[100] = "nahin bin kaysar";     const char s[2] = " ";     char *token;      token = strtok(str, s);     printf("%s", token);     while (token != null) {         puts(token);         token = strtok(null, s);     }      return 0; } 

in case, if have questions after reading documentation other thread maybe can out.


Comments