I'm new to the "->" symbol, so I'm instead replacing it with (*). . However, when I came across the line of code below, I tried replacing it and it didn't work. What am I doing wrong and is there any way to rewrite it?
I keep getting the error that "key" is a pointer and when I rewrite it, it doesn't work. I have triple checked my code, and yet I still don't understand.
struct Node{
int key;
Node *left;
Node *right;
};
Node* createNode(int key){
Node *node = new Node();
(*node).key = key;
(*node).left = NULL;
(*node).right = NULL;
return node;
}
int main(){
Node *root = createNode(1);
(*root).left = createNode(9);
cout << root->left->key; // Correct?
cout << " OR ";
cout << ((*root).left).(*key);
// this is where my code goes wrong and if I remove the (*) from key
// and just leave it like .key it's wrong because key has to be a pointer
return 0;
}
I expect the output to be "9 OR 9" but it doesn't even let me compile past that point.
If you really want to avoid the ->
operator, you can write it like this:
cout << (*((*root).left)).key;
... but that's painful to write and painful to read, so it makes a great example of why the ->
operator is useful :)