Sending pointer to function
Dec 8, 2010 at 9:22am UTC
Hello,
I have an object with three pointers to another three objects.On my main, I am trying to send a pointer to this object. The problem is that the internal pointers are not returning the values. Could you please advice me what the problem is?
Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#include <iostream>
#include <cmath>
using namespace std;
class nodeTree
{
public :
int value;
nodeTree *son1,*son2,*son3;
nodeTree(int v){son1=son2=son3=NULL;value=v;}
void add(nodeTree newa,nodeTree newb,nodeTree newc)
{
this ->son1=&newa;
this ->son2=&newb;
this ->son3=&newc;
}
};
void calcMax(nodeTree *);
int main()
{
nodeTree myRoot(2);
nodeTree a1(4);
nodeTree a2(5);
nodeTree a3(6);
myRoot.add(a1,a2,a3);
cout<<myRoot.son1->value;//prints ok
calcMax(&myRoot);
}
void calcMax(nodeTree *t)
{
cout<<t->son1->value; //garbage, not expected value,why?
}
Last edited on Dec 8, 2010 at 12:00pm UTC
Dec 8, 2010 at 12:21pm UTC
void add(nodeTree newa,nodeTree newb,nodeTree newc)
Parameters are passed by value. It should be:
1 2 3 4 5 6
void add(nodeTree *newa, nodeTree *newb, nodeTree *newc)
{
son1=newa;
son2=newb;
son3=newc;
}
Dec 8, 2010 at 12:37pm UTC
Great, it is working!!Thanks!!
Topic archived. No new replies allowed.