#include <iostream> using namespace std; class Marks { public: char* name(); }; char* Marks::name() { char temp[30]; cout<<'Enter a name:'<<endl; cin.getline(temp,30); return temp; } int main () { char *name; Marks test1; name=test1.name(); //cout<<'name:'; //uncomment this line to see the problem cout<<name<<endl; return 0; }
#include <iostream> using namespace std; class Marks { public: char* name(); }; char* Marks::name()
Share
The problem is because the value that name is pointing to has been destroyed. You are returning the address of a local variable from
Marks::name(). Most likely a side affect of the firstcoutis causing the contents ofnameto be destroyed. You’re probably just getting lucky when the firstcoutis commented out.The correct way to do this is to allocate some memory, return that, and then destroy it when you’re done:
Don’t forget to use
delete[], rather than justdelete, since otherwise only the first character would be deallocated.