Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pointers doubts

I have a doubt about this code I saw at the university.

struct nodeList{
  int data;
  nodeList * next;
};
typedef nodeList * List;

void filter( List &l )
{
   List * aux = &l;
   while(*aux)
   {
       if( (*aux)->data > 3 )
       {
          List toDelete = *aux;
          *aux = (*aux)->next;
          delete toDelete;
       }
       else
       {
          aux = &((*aux)->next);
       }   
   }
}
  • I don't know, what does List * aux = &l; actually do. Because List is the same as nodeList * so, the code would be nodeList * * aux = &l; and that is actually what I don't understand, is that a pointer to a pointer that holds the address of a pointer of a nodeList struct?

  • The second thing I have trouble understanding is the last line. aux = &((*aux)->next); Why is aux without a * on the left side? if It was declared as List *aux = &l; is List just a pointer to the first node?

Thank you in advance. I googled a lot, but I didn't find any answers. If you can answer my questions I'll appreciate a lot.

like image 289
HoNgOuRu Avatar asked Jul 26 '14 18:07

HoNgOuRu


1 Answers

  1. Exactly.

  2. You should always match the datatypes. aux is a nodeList **, therefore any assignment should be of the same datatype. Since ((*aux)->next) is nodeList *, you use the & operator to get a nodeList **.

Datatypes

Variables have specific datatypes. For example, aux is a List* but List is an alias of nodeList*, so aux is a nodeList**.

But also expressions have datatypes as a whole. For example,

  • the expression ((*aux)->next) is of datatype nodeList * and &((*aux)->next) is of datatype nodeList **. You use the operator & to get the memory address of a variable, and the result data type of using & is one more star.
  • the expression *aux is of datatype nodeList *, because aux is nodeList ** and the star operator gets the value of the pointed element by the pointer, effectively removing one star from the datatype.
like image 133
vz0 Avatar answered Oct 13 '22 07:10

vz0