Search code examples
cstringtokenizestrsep

Storing pointers to strsep() return values


When I use strsep() to iterate through the tokens of a string, is it safe for me to store pointers to those tokens, and refer to them later? Example:

char str[] = "some word tokens";
char *sameStr = str;
char *token, *old1, *old2;

token = strsep(&sameStr, " ");
old1 = token;

token = strsep(&sameStr, " ");
old2 = token;

token = strsep(&sameStr, " ");

printf("%s\n%s\n%s\n", token, old1, old2);

It seems like strsep() always modifies the original character array, inserting null characters after each token. If so, I should be safe storing and later using the old1 and old2 pointers, right? Also, does my use of sameStr cause any problems? I can't use the pointer str directly due to strsep() expecting a restricted char** type.


Solution

  • The stored pointers will be valid until the original string goes out of scope. Until then, you can access them however you need to. The use of sameStr shouldn't cause any problems.