Search code examples
cstringprintfstrtok

strtok() as a parameter in printf() printing value in reverse


If you have a string as below str="insert 111,name,123456789" when you pass it to strtok and try to print the values, they are output in reverse. For example:

char* token=strtok(str," ");
printf("%s %s %s %s\n",token,strtok(NULL,","),strtok(NULL,","),strtok(NULL,","));
output: insert 1234567 name 1111

instead of:insert 111 name 123456789 Why is this happening? How can this be fixed?


Solution

  • parameters are pushed to the stack in the Calling Convention order, which in your case, reverse... therefore parameter 5 is first to evaluate and pushed in the stack, then 4,3,2 and the format string.

    as many comments before suggested, your call style is very discouraged, and should be avoided.