I was under the impression that it was possible to access data from a sub-node of a linked list or similar structure by using the arrow and dot operators together like so:
typedef struct a{
int num;
struct a *left;
struct a *right;
}tree;
tree *sample;
...
if(sample->left.num > sample->right.num)
//do something
but when I try to implement this, using -> and . to access data from a sub node I get the error "request for member num in something not a structure or union".
An Arrow operator in C/C++ allows to access elements in Structures and Unions. It is used with a pointer variable pointing to a structure or union. The arrow operator is formed by using a minus sign, followed by the greater than symbol as shown below.
You use . if you have an actual object (or a reference to the object, declared with & in the declared type), and you use -> if you have a pointer to an object (declared with * in the declared type).
Yes, dot (.) is actually an operator in C/C++ which is used for direct member selection via object name. It has the highest precedence in Operator Precedence and Associativity Chart after the Brackets.
Use ->
for pointers; use .
for objects.
In your specific case you want
if (sample->left->num > sample->right->num)
because all of sample
, sample->left
, and sample->right
are pointers.
If you convert any of those pointers in the pointed to object; use .
instead
struct a copyright;
copyright = *(sample->right);
// if (sample->left->num > copyright.num)
if (*(sample->left).num > copyright.num)
Since I don't see it mentioned explicitly:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With