I have recently faced a problem of creating the self-referential structures. Whenever I try to use them, the program behaves weirdly. Take, for instance, the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
struct N
{
int value;
N *left;
N *right;
}N;
int main()
{
N.value = 1;
N.right->value = 2;
N.right->right->value = 3;
N.right->right->right->value = 4;
cout<<N.right->right->right->value;
return 0;
}
You're not doing it correctly. You can't dereference right (or left) with -> (or *) when the pointer hasn't been set to point to allocated memory. You need to allocate memory for the new nodes with the "new" operator.
#include <iostream>
struct N {
int value;
N *left;
N *right;
};
int main() {
N n;
n.value = 1;
n.right = new N;
n.right->value = 2;
n.right->right = new N;
n.right->right->value = 3;
n.right->right->right = new N;
n.right->right->right->value = 4;
std::cout << n.right->right->right->value << '\n';
// We should probably be setting all the "left" pointers of the new nodes to null since they don't point to anything.
// And we should usually "delete" the allocated memory, but we can leave that to the OS.
}