Below are 3 functions. main() prints out as expected. Now, in mycharstack() the string is stored on stack I guess, so as "ch" goes out of scope, it should not be able to return the string. How does it work correctly? I guess the string stored in mychar() is also on stack. Is it supposed to work correctly? I guess there are other errors in the code and memory leaks, please let me know if any. I could do these cleaner & easier with std::string. But I want to understand what's going on with char*.
#include <iostream>
using namespace std;
char* mychar()
{
return "Hello";
}
char* mycharstack()
{
char* ch = "Hello Stack";
return ch;
}
char* mycharheap()
{
char* ch = new char;
ch = "Hello Heap";
return ch;
}
int main()
{
cout << "mychar() = " << mychar() << endl;
cout << "mycharstack() = " << mycharstack() << endl;
cout << "mycharheap() = " << mycharheap() << endl;
system("PAUSE");
return 0;
}