Let's say i have the following structs:
struct Foo
{
int val;
};
struct Test
{
Foo *bar;
};
and I wanted to create a Test
struct:
Test get_test()
{
Test test;
Foo foo;
foo.val = 10;
test.bar = &foo;
cout << "INIT: " << test.bar->val << endl;
return test;
}
int main()
{
Test test = get_test();
cout << "AFTER: " << test.bar->val << endl;
return 0;
}
The output is the following:
INIT: 10
AFTER: 32723
I tried to do this differently:
Test get_test()
{
Test test;
Foo *foo;
foo->val = 10;
test.bar = foo;
cout << "INIT: " << test.bar->val << endl;
return test;
}
But this gave me a SIGSEGV (Address boundary error)
From my limited understanding, I believe it is because in get_test()
foo
is a temporary variable, so the reference doesn't mean anything. How can I do this properly?