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);
}
}
What is the **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.
QUEUE** qptrmeans thatqptris a pointer to a pointer to aQUEUE(whatever that is).*qptris “the memory pointed to byqptr“, which is thus a pointer to aQUEUE.x->yis the same as(*x).y. In other words, “take the thing pointed to byx, then get itsy“. See https://stackoverflow.com/a/3479169/383402 for reference.So,
(*qptr)->headis theheadof theQUEUEwhich is pointed to by the thing which is pointed to byqptr.The extra layer of indirection is so that the function can effectively return a
QUEUE*. In order to return theQUEUE*, it takes in aQUEUE**, and makes it point to the newly-allocated memory.