队列函数的棘手 C 代码,指针发生了什么?
我试图理解这个用于修改队列的 C 代码:
/*
* 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
参数? (*qptr)->head
是什么意思?我知道->是一个指向结构成员引用的指针,但我不知道这里发生了什么。我很感激任何提示或建议。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
QUEUE** qptr
意味着qptr
是一个指向QUEUE
的指针(无论它是什么)。*qptr
是“qptr
指向的内存”,因此它是一个指向QUEUE
的指针。x->y
与(*x).y
相同。换句话说,“获取x
指向的东西,然后获取它的y
”。请参阅 https://stackoverflow.com/a/3479169/383402 以供参考。因此,
(*qptr)->head
是QUEUE
的head
,它由所指向的事物所指向。到qptr
。额外的间接层使函数可以有效地返回
QUEUE*
。为了返回QUEUE*
,它接受QUEUE**
,并使其指向新分配的内存。QUEUE** qptr
means thatqptr
is a pointer to a pointer to aQUEUE
(whatever that is).*qptr
is "the memory pointed to byqptr
", which is thus a pointer to aQUEUE
.x->y
is 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)->head
is thehead
of theQUEUE
which 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.