Código C complicado para la función de cola, ¿qué está sucediendo con los punteros?

I'm trying to understand this C code for modifying queues:

  /*
    * create or delete a queue
    * PARAMETERS: QUEUE **qptr - space for, or pointer to, queue
    * int flag -  1 for create, 0 for delete
    * int size - max elements in queue
    */
    void qManage(QUEUE **qptr, int flag, int size){
         if(flag){
                  /* allocate a new queue */
                  *qptr = malloc(sizeof(QUEUE));
                  (*qptr)->head = (*qptr)->count = 0;
                  (*qptr)->que = malloc(size * sizeof(int));
                  (*qptr)->size = size;
                  }
                  else{
                       // delete the current queue
                       (void) free((*qptr)->que);
                       (void) free(*qptr);
                 }
           }

¿Qué es **qptr parameter? What does (*qptr)->head mean? I know that -> is a pointer to a structure member reference, but I'm lost on what's going on here. I appreciate any tips or advice.

preguntado el 01 de febrero de 12 a las 04:02

Busca un typedef para QUEUE type. It'll be a struct que tendrá un head member... -

@sarnold - cool, I see what you mean, yes there's a struct with int head -

1 Respuestas

QUEUE** qptr significa que qptr es un puntero a un puntero a un QUEUE (sea lo que sea).

*qptr is "the memory pointed to by qptr", which is thus a pointer to a QUEUE.

x->y es el mismo que (*x).y. In other words, "take the thing pointed to by x, luego obtén su y". Ver https://stackoverflow.com/a/3479169/383402 para referencia.

¿Entonces (*qptr)->head es la head de los QUEUE which is pointed to by the thing que es señalado por qptr.

The extra layer of indirection is so that the function can effectively return a QUEUE*. In order to return the QUEUE*, it takes in a QUEUE**, and makes it point to the newly-allocated memory.

contestado el 23 de mayo de 17 a las 15:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.