Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using arrow -> and dot . operators together in C

Tags:

c

binary-tree

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

like image 410
Daniel Nill Avatar asked Apr 30 '11 22:04

Daniel Nill


People also ask

What is the -> operator in C?

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.

What's the difference between and -> in C++?

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

Can we use dot operator in C?

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.


2 Answers

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)
like image 141
pmg Avatar answered Sep 17 '22 17:09

pmg


Since I don't see it mentioned explicitly:

  • Use -> to dereference the pointer on its left hand side and access the member on its right hand side.
  • Use . to access the member on its right hand side of the variable on its left hand side.
like image 38
Mel Avatar answered Sep 20 '22 17:09

Mel