Problem with function returning vector<node*>

Can someone tell me why the following happens:

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
#include<cstdio>
#include<iostream>
#include<vector>
using namespace std;
class node{
	public:
		int f;
		int g;
};

vector<node*> func(node a){
	vector<node*> x;
	node s=a;
	s.f=0;
	x.push_back(&s);
	cout<<x[0]<<endl; // the address of node
	cout<<((*x[0]).f)<<endl; // the output is 0
	return x;
}
int main(){
	node a;
	vector<node*> x=func(a);
	cout<<x[0]<<endl; // the address of node
	cout<<((*x[0]).f)<<endl; // the output is 10
	return 0;
}



The value of x[0](which is address of the node) is same at both the places but the value of (*x[0]).f is different in func() and main().

Thanks.
In func you add a pointer to s which is a local object. s will stop to exist at the end of the function. On line 24 you try to print the value of a non existing object, which will give you unpredictable output.
Last edited on
wow,didn't knew that... Thanks a lot Peter87!!!
Topic archived. No new replies allowed.