Pointer Issues

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?

1
2
3
4
5
6
7
 struct Node
    {
        int data;
        Node *left;
        Node *next;
    };
      vector<Node *> array;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
	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
		}
	}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	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);
		}
	}
Last edited on
Have you tried cout << hold[i]->data << endl;?
Yes I have and it print unreadable characters and and then terminates with a seg fault error
In search(), what is x->element ? Your node structure doesn't have a "element" member.

How did you fill your array ? A seg fault seems to indicate that you have not allocated memory for your objects.
Last edited on
line 13 of the search function.
If recursively called search finds something, where will result go?

In fact, if it will not find needed data immideatly, it will return random number from the stack.
So you trying to dereference a pointer to random memory address

And like toum said, you don't have an "element" member in "Node" struct. Did you misspelled "data"?
Last edited on
Topic archived. No new replies allowed.