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...
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];
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With