Announcements Last Post
Announcement SoC Curricula 09/30/2017 01:08PM
Announcement Demarcation or scoping of examinations and assessment 02/13/2017 07:59AM
Announcement School of Computing Short Learning Programmes 11/24/2014 08:37AM
Announcement Unisa contact information 07/28/2011 01:28PM
Pointer Problem
September 06, 2006 05:44PM
The following program defines a function that is supposed to return a pointer of a string variable to the main program. Strangely, the program compiles but crashes when it runs. It crashes where it attempts to derefrerence the pointer in the main program.

Please assist:

#include <iostream>
#include <conio.h>
#include <string>

using namespace std;

string *acceptName() {
string name;
cin>> name;

return &name;
}

int main() {
string *name (acceptName());

cout<< "Your name is "<< *name<< endl;
getche();
return 0;
}



Shupi
Anonymous User
Re: Pointer Problem
September 09, 2006 11:39AM
"Local variables are destroyed and their memory reclaimed at the end of the enclosing block." - cprogramming.com
That means that you are making reference to a memory location that does not exist anymore. One way to get around this is to use a global variable as in the next example.

#include <iostream>
#include <string>
using namespace std;

string name;

string *acceptName(){
cout << "Name:";
cin>> name;
return &name;
};

int main() {
string *name;
name = acceptName();

cout<< "Your name is "<< *name<< endl;
return 0;
}


This works fine - but as you know Global varaibles is not such a good idea.I will look for some more ways to work around this.
Re: Pointer Problem
September 10, 2006 12:35PM
Thanks buddie, it had never occurred to me to consider a global variable.

However, like what u said, the use of a global variable may not be the best solution if ever there is another way to do it.

Cheers,

Shupi
Re: Pointer Problem
September 10, 2006 02:30PM
this should fix your problem without the use of global variables

#include <iostream>
#include <string>

using namespace std;

string *acceptName() 
{
	string *name = new string;
	cout << "Enter name: ";
	getline(cin, *name, '\n');  //  or cin >> *name;	
	return name;
}

void main() 
{
	string *name(acceptName());
	cout<< "Your name is "<< *name << endl;
        delete name;
}
Sorry, only registered users may post in this forum.

Click here to login