2

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.

Pat Flegit
  • 183
  • 1
  • 2
  • 11
  • Not only *seems* like it overwrite the contents in the string you pass. It *definitely* does that. From [this manual page](http://man7.org/linux/man-pages/man3/strsep.3.html): "This token is terminated by overwriting the delimiter with a null byte ('\0')" – Some programmer dude Mar 21 '16 at 13:43

1 Answers1

3

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.

owacoder
  • 4,815
  • 20
  • 47