I was trying to return a pointer to a structure from a function. I wrote the following code but it did not work and gave a segmentation fault.
#include <iostream>
using namespace std;
struct Node {
int val;
Node* next;
Node(int x): val(x), next(NULL) {};
};
Node* f(int a){
Node x = Node(10);
return &x;
}
int main(){
Node *x = f(10);
cout << x->val << "\n";
return 0;
}
Whereas the following piece of code worked fine.
#include <iostream>
using namespace std;
struct Node {
int val;
Node* next;
Node(int x): val(x), next(NULL) {};
};
Node* f(int a){
Node *x = new Node(10);
return x;
}
int main(){
Node *x = f(10);
cout << x->val << "\n";
return 0;
}
Why is the first code not working whereas the second one is working?