I’m reading a string with space as a delimiter by using the strtok function.
My code looks like this:
char * pch = strtok (text," ");
int i = 0;
while (pch != NULL)
{
if (i == 0)
strcpy(name, pch);
else
others[i - 1] = pch;
pch = strtok (NULL, " ");
}
The string looks like this: TCP 1 2 3 4, and name is of char* type that I receive in my function.
I wish to assign name to be TCP (i.e. first piece before the first delimiter), but because the pch pointer proceeds, the name variable changes when pch changes. How can I assign the pch pointer value to name without it being changed when the pointer changes?
You never increment
iso every loop ends up copying the latest value ofpchintoname.You could fix it by incrementing
ifor each iteration of the loop: