C++ : Why I can't print a const char* with sprintf?

c++, constants, pointers, printf, string

Solution

You're trying to return an array allocated on stack and its behaviour is undefined.

const char* Notation() const
{
    char s[10];
    int x=5;
    sprintf(s, "%d", x);
    return s;
}

here `s` isn't going to be around after you've returned from the function `Notation()`. If you aren't concerned with thread safety you could make `s` static.

const char* Notation() const
{
    static char s[10];
    ....

Problem

What am I missing here ? It's driving me nuts ! I have a function that returns a const char* ``` const char* Notation() const { char s[10]; int x=5; sprintf(s, "%d", x); return s; } ``` Now in another part of the code I am doing this : ``` ..... ..... char str[50]; sprintf(str, "%s", Notation()); ..... ..... ``` but str remains unchanged. If instead I do this : ``` ..... ..... char str[50]; str[0]=0; strcat(str, Notation()); ..... ..... ``` str is correctly set. I am wondering why sprintf doesn't work as expected...

Original source