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

What am I missing here? It drives me crazy!

I have a function that returns 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 I do this:

.....
.....
char str[50];
str[0]=0;
strcat(str, Notation());
.....
.....

str .

I am wondering why sprintf does not work as expected ...

+5
source share
3 answers

You are trying to return an array allocated on the stack and its behavior is undefined.

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

there swill not be around after you return from the function Notation(). If you don't care about thread safety, you can do a static one s.

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

undefined, Notation() , . , , , .

, std::string :

std::string Notation() const
{
    char s[10];
    int x=5;
    sprintf(s, "%d", x);
    return s; //it is okay now, s gets converted into std::string
}

++ :

std::string Notation() const
{
    int x=5;
    std::ostringstream oss;
    oss << x;
    return oss.str(); 
}

:

char str[50];       
sprintf(str, "%s", Notation().c_str());

( ) std::ostringstream ( std::string) , , , , 10 char s[10]. .

+5

char s[10] Notation , Notation. automatic. , new:

char *s = new char[10];

:

char str[50];
const char *nt = Notation();
sprintf(str, "%s", nt);
printf("%s", str);
delete[] nt;

If you really use C ++ then use a built-in stringclass like Nawaz . If you are somehow restricted by crude pointers, highlight the buffer outside Notationand pass it as a drop parameter, for example, to sprintfor strcat.

+1
source

All Articles