In the following, I’m trying to split string without creating copies using strok
#include <string.h>
void func(char *c)
{
char *pch = strtok (c,"#");
while (pch != NULL)
{
pch = strtok (NULL, "#");
}
}
int main()
{
char c[] = "a#a\nb#b\n";
char *pch = strtok (c,"\n");
while (pch != NULL)
{
char *p = new char[strlen(pch)+1];
strcpy(p, pch);
func(p); //copy of pch
pch = strtok (NULL, "\n"); //fails to get pointer to 'b#b'
}
}
Uhm…
strtok()may store the tokenized string in a static buffer. Hence, when secondstrtok()is called in thefunc(), the results of the first operation (in themain()) seem to be lost. Take a look atstrtok_r().