Confusion using strtok

Im using strtok and a little confused.

I have an array containing many rows, and I want to tokenize the rows in a temporary array. When I execute strtok, it stores the first token in a temporary array, but also changed the original value of the array. So I was very 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]); 

Exit

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

How to save the original values ​​in the team?

+4
source share
2 answers

Make strtok on a copy of the string.

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

If you don't / want to use strdup :

 char *copy = malloc(strlen(commands[0]) + 1); strcpy(copy, commands[0]); /* ... */ 
+6
source

strtok changes its input.

This is a bad old feature. Unfortunately.

If you want to keep the original and call strtok (instead of strstr or another such alternative), you will need to copy the line before the first call.

0
source

Source: https://habr.com/ru/post/1393535/


All Articles