Parentheses in a pointer to pointer

Asked

Viewed 59 times

2

I’m studying a binary tree structure and I got in doubt in a part of the code.

#include <stdio.h>
#include <stdlib.h>

typedef struct tree
{
  int num;
  struct tree* sad;
  struct tree* sae;
} Tree;

void insertTree(Tree** t, int num)
{

  if(*t == NULL)
  {
    *t = (Tree*)malloc(sizeof(Tree)); 
    (*t)->sae = NULL; 
    (*t)->sad = NULL;
    (*t)->num = num;
  }
}
// Código continua, porém não achei necessário colocá-lo 

int main()
{
  Tree* t = NULL;

  insertTree(&t, 12);
}

My doubt is precisely when you have this parentheses on the pointer (*t)->sae = NULL;

What does he mean?

1 answer

2


There is a operator precedence table, as you know in mathematics (multiplication and division happens before addition and subtraction). In case a code of a language has several operators.

tabela de precedência de operadores em C

As it is possible to see in the table the parentheses have maximum precedence so everything inside it will be done before.

(1 + 2) * 4

gives 12, is different from

1 + 2 * 4

which gives 9 because in fact this is what happens implicitly:

1 + (2 * 4)

The pointer has a slightly lower precedence. But a member’s pointer has the maximum precedence, so if you have a normal pointer and a member’s pointer will be solved before. Unless you have parentheses forcing new precedence. So

*t->num

takes the value of t and then tries to take the object referenced by num (->). Then what he finds will try to drift with the *. This will be a mistake, it makes no sense.

What you’re doing in your code is derreferencing t with * first and the result of this is that you should take the object referenced by num (->). So you have to ensure that the pointer (*) run before the member pointer (->).

(*t) -> num

The pattern with nothing would be the same as writing like this:

*(t->num)

I put in the Github for future reference.

It’s not what you want.

The (*t) -> num is holding something in the limb num, which is what is desired.

The *(t->num) is holding something in place that t->num indicate, that is not what you want.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.