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");
}
pvdg42 - 04 Mar 2007 14:10 GMT
> Hi -- I'm just starting to learn about pointers and I'm stuck on
> something.
[quoted text clipped - 40 lines]
> system("PAUSE");
> }
If you want to access the new Widget in main() you need to change the
definition of your changer() function to return a pointer to widget.
Something like this:
widget* changer (int i, widget *x)
{
cout << i << "\n";
x = new widget;
(*x).info = i;
cout << (*x).info << "\n";
return x;
}
Then change your call to: w = changer(10, w);
Vincent Fatica - 04 Mar 2007 17:12 GMT
The whole point of passing the pointer is that changer() have a widget to work
with. Changer shouldn't be creating a new widget (you mentioned no reason to do
so). Inside changer(), *x is a pointer to the existing widget (which I think is
exactly what you want it to be). Try this:
void changer (int i, widget *x)
{
cout << "Before: " << (*x).info << "\n";
(*x).info = i;
cout << "After: " << (*x).info << "\n";
}
Perhaps you are unaware of a slightly more efficient notation for referencing a
member given a pointer:
void changer (int i, widget *x)
{
cout << x->info << "\n";
x->info = i;
cout << x->info << "\n";
}
Output:
12
12
10
10
>class widget
>{
[quoted text clipped - 23 lines]
> system("PAUSE");
>}

Signature
- Vince
David Wilkinson - 04 Mar 2007 17:33 GMT
> 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
[quoted text clipped - 38 lines]
> system("PAUSE");
> }
Bill:
1. You have two new's in your code without any delete's, so you will
leak memory.
2. Worse, the new in changer() is what stops your code form working.
3. Use the -> operator.
4. It's int main() not void main().
5. Class widget should have a constructor.
#include <iostream>
using namespace std;
class widget
{
public:
widget():info(0){}
int info;
};
void changer (int i, widget *x)
{
cout << i << "\n";
x->info = i;
cout << x->info << "\n";
}
int main()
{
widget w;
w.info = 12;
cout << w.info << "\n";
changer (10, &w);
cout << w.info << "\n"; //I want this to output 10 not 12.
system("PAUSE");
return 0;
}