I am having issue returning a pointer to a struct. Can some explain what I am doing wrong? I want the search() to return a pointer to the matching input. That will be stored into a vector in case their are duplicates in the “array”. This seems to work however I cannot get the “data” from the pointer returned?
struct Node
{
int data;
Node *left;
Node *next;
};
vector<Node *> array;
void find(int & input)
{
currentSize = 0;
vector<Node *> hold;
for( int i = 0; i < array.size( ); i++ ){
if(search(array[i], input) != NULL)
{
hold.push_back(search(array[i], input));
}
else{
cout << "The Key is not found" << endl;
}
}
for(int i = 0; i < hold.size(); i++)
{
cout << hold[i] << endl;
//Problem here:: I want to see the "data" that the search function returned not the hex value
}
}
Node * search(Node * x, const int & input)
{
if( x == NULL )
{
return NULL;
}
else
{
if(input == x->element)
{
return x;
}
search(x->left, input);
search(x->next, input);
}
}
You need to turn compiler warnings on.
Not all code paths of search return a value, in particular, is the warning you should be getting if your compiler isn’t being brain dead.
To fix this, replace this:
with:
The
search()recursive calls do not automatically ferry their return values over to the return value of the current function. 🙂In addition, as noted by Zack, you need to look at some subfield of the
Nodeto print it. First check if the return value isnullptr(orNULLin non-C++11 capable compilers) (if it is null, you can’t dereference it safely, and it indicates the search failed).If it isn’t
nullptr‘, do a->dataon it before you print.Ie, change:
to:
note that I’m not using
std::endl, because I don’t see the need to flush the buffer on each line.