Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 514
Wartin Avatar asked May 27 '12 05:05

Wartin


1 Answers

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];
    ....
like image 200
hawk Avatar answered Sep 26 '22 17:09

hawk