最近,在我当前项目中读取前代码时,我遇到了以下问题:
在实现Queue时,我以前编写的代码如下:
while(uq->pHead)
{
char *tmp = uq->pHead;
uq->pHead = *(char **)tmp;
//...
}
Run Code Online (Sandbox Code Playgroud)
uq-> pHead的定义如下:
typedef struct {
char* pHead;
//...
} Queue;
Run Code Online (Sandbox Code Playgroud)
嗯,我对" uq->pHead = *(char**)tmp
" 的使用感到很困惑,有人能详细解释一下吗?
如果我们假设*(uq-> pHead)= 32(即''),*(char**)tmp
将其转换为指针形式,但......它怎么会有意义?
非常感谢.
我们假设我们将您的队列实现为链接列表.我们可能有:
struct data_type;
struct node
{
node *next;
data_type item;
};
struct linked_list
{
node *pHead;
// ...
};
Run Code Online (Sandbox Code Playgroud)
要清空链表,我们可能会写:
linked_list *uq=...;
while (uq->pHead)
{
// unlink the first node from the list
node *tmp = uq->pHead;
uq->pHead = tmp->next;
// do something with that node
// ...
// deallocate the node
free(tmp);
}
Run Code Online (Sandbox Code Playgroud)
现在假设我们并不真正关心可维护的代码,或者其他方面都是懒惰的.我们可能只是想象任何指针都会做,并将'node'的结构保留在我们的头脑中,然后写:
linked_list *uq=...;
while (uq->pHead)
{
// unlink the first node
char *tmp = uq -> pHead; // tmp points to the first 'node'
uq -> pHead = *(char**)tmp; // The first thing in a 'node' is a pointer to
// the next node.
// do something with 'tmp', the now unlinked node
data_type *item=(data_type*) ( ((char**)tmp) + 1 ); // after the 'next' pointer
// is the real data.
// ...
// free up the node
free(tmp);
}
Run Code Online (Sandbox Code Playgroud)