Reputation: 12484
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.
Upvotes: 0
Views: 395
Reputation: 98479
QUEUE** qptr
means that qptr
is a pointer to a pointer to a QUEUE
(whatever that is).
*qptr
is "the memory pointed to by qptr
", which is thus a pointer to a QUEUE
.
x->y
is the same as (*x).y
. In other words, "take the thing pointed to by x
, then get its y
". See https://stackoverflow.com/a/3479169/383402 for reference.
So, (*qptr)->head
is the head
of the QUEUE
which is pointed to by the thing which is pointed to by 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.
Upvotes: 5