G
Guest
Hi -- I'm just starting to learn about pointers and I'm stuck on something.
The code that I pasted below passes a widget object to a function that
changes it to a new widget object. It changes it successfully within the
changer() function but once execution returns to main(), the "w" variable
still stores to the original widget. How can I change this code so that "w"
stores the new widget?
Thanks for your help,
P.S. VS.NET 2003.
Bill
#include <iostream>
using namespace std;
class widget
{
public:
int info;
};
void changer (int i, widget *x)
{
cout << i << "\n";
x = new widget;
(*x).info = i;
cout << (*x).info << "\n";
}
void main()
{
widget *w;
w = new widget;
(*w).info = 12;
cout << (*w).info << "\n";
changer (10, w);
cout << (*w).info << "\n"; //I want this to output 10 not 12.
system("PAUSE");
}
The code that I pasted below passes a widget object to a function that
changes it to a new widget object. It changes it successfully within the
changer() function but once execution returns to main(), the "w" variable
still stores to the original widget. How can I change this code so that "w"
stores the new widget?
Thanks for your help,
P.S. VS.NET 2003.
Bill
#include <iostream>
using namespace std;
class widget
{
public:
int info;
};
void changer (int i, widget *x)
{
cout << i << "\n";
x = new widget;
(*x).info = i;
cout << (*x).info << "\n";
}
void main()
{
widget *w;
w = new widget;
(*w).info = 12;
cout << (*w).info << "\n";
changer (10, w);
cout << (*w).info << "\n"; //I want this to output 10 not 12.
system("PAUSE");
}