4

Im using strtok and getting a little confused.

I have an array holding a lot of strings and I want to tokenize the strings into a temporary array. When i perform the strtok it stored the first token in the temporary array, but also changed the original arrays value. So im pretty confused.

char cmdTok[10] , *cmd = cmdTok;
printf("command[0] = %s\n", commands[0]);
cmd = strtok(commands[0], " \n\0");
printf("command[0] after strtok = %s\n", commands[0]);

Output being

command[0] = #Draw A Ring
command[0] after strtok = #draw

How do i retain the original values in command?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
meriley
  • 1,831
  • 3
  • 20
  • 33

2 Answers2

6

Do the strtok on a copy of the string.

char *copy = strdup(commands[0]);
cmd = strtok(copy, " \n");
/* ... */

free(copy);

If you don't have / want to use strdup:

char *copy = malloc(strlen(commands[0]) + 1);
strcpy(copy, commands[0]);
/* ... */
cnicutar
  • 178,505
  • 25
  • 365
  • 392
0

strtok modifies its input.

It's a bad old function. Sorry.

If you want to both preserve the original and call strtok (instead of strstr or another such alternative), you're going to have to copy the string out before the first call.

Borealid
  • 95,191
  • 9
  • 106
  • 122