Using arrow -> and dot . operators together in C

Daniel Nill picture Daniel Nill · May 1, 2011 · Viewed 20.6k times · Source

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".

Answer

pmg picture pmg · May 1, 2011

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)