B
becte
I encountered the following code similar to this
// some header files
static char* func(int i)
{
ostrstream out;
if (i==1) out << "ABCDE";
else if (i==2) out << "123";
else cout << "";
return out.str();
}
int main ()
{
static char *p1 = NULL, *p2 = NULL;
p1 = func(1);
p2 = func(2);
printf ("String1 = %s, String2 = %s\n", p1, p2);
return 0;
}
The desired out put is "String1 = ABCDE, String2 = 123".
New if I used an character array, char out[10], and returning &out[0]
instead of ostrstream this would definitly be illegal.
But this looks illegal too, I suppose ostrstream has some destructor
that deletes any allocated memory. What is confusing is that this
happens to work when i try it. Is this legal after all?
// some header files
static char* func(int i)
{
ostrstream out;
if (i==1) out << "ABCDE";
else if (i==2) out << "123";
else cout << "";
return out.str();
}
int main ()
{
static char *p1 = NULL, *p2 = NULL;
p1 = func(1);
p2 = func(2);
printf ("String1 = %s, String2 = %s\n", p1, p2);
return 0;
}
The desired out put is "String1 = ABCDE, String2 = 123".
New if I used an character array, char out[10], and returning &out[0]
instead of ostrstream this would definitly be illegal.
But this looks illegal too, I suppose ostrstream has some destructor
that deletes any allocated memory. What is confusing is that this
happens to work when i try it. Is this legal after all?