Page 1 of 1

cpvstr

Posted: Fri Apr 11, 2008 1:22 am
by juanpi
Hi,
The line
printf("%s %s\n", cpvstr(body1->p),cpvstr(body2->p))

gives a different result than

printf("%s ", cpvstr(body1->p));printf("%s\n",cpvstr(body2->p))

Where the second call gives the correct output.

I looked at the function but I can not see why is this?

Thanks!

Re: cpvstr

Posted: Fri Apr 11, 2008 4:39 am
by supertommy
Look at cpvstr:

Code: Select all

char*
cpvstr(const cpVect v)
{
    static char str[256];
    sprintf(str, "(% .3f, % .3f)", v.x, v.y);
    return str;
}
It returns a pointer to a function-static character array. This means that the call to cpvstr(body2->p) will overwrite the string generated in cpvstr(body1->p). Doing this in two printfs works because you will print the first string before overwriting it with the second.

Re: cpvstr

Posted: Fri Apr 11, 2008 10:09 am
by slembcke
From the documentation:
NOTE: The string points to a static local and is reset every time the function is called.
Sorry. If you need something fancier, you'll have to split up your printf() calls or stringify them yourself.

Re: cpvstr

Posted: Fri May 16, 2008 1:52 am
by juanpi
Thanks!
I had read the note in the documentation but was not sure of what it meant.
I guess is because an incomplete knowledge of how multiple arguments to printf are treated. Heuristic approach to programming, jejeje
:D