Interview Question
Software Engineer / DevelopersGenerates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.
A terminating null character is automatically appended.
The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only granted to remain unchanged until the next call to a non-constant member function of the string object.
This would work:
const char *myfunc()
{
char *cstr;
string str("return this");
cstr = new char [str.size()+1];
strcpy (cstr, str.c_str());
return cstr;
}
returning pointer to stack variable which will be deleted as soon as function returns
- sachin323 November 01, 2010