在最近的Slashdot Interview篇文章中,Linus Torvalds举了一个例子,说明一些人使用指针的方式表明他们并不真正理解如何正确使用指针.

不幸的是,由于我是他所说的人之一,我也未能理解他的例子:

I've seen too many people who delete a singly-linked list entry by keeping track of the "prev" entry, and then to delete the entry, doing something like

if (prev)
    prev->next = entry->next;
else
    list_head = entry->next;

and whenever I see code like that, I just go "This person doesn't understand pointers". And it's sadly quite common. People who understand pointers just use a "pointer to the entry pointer", and initialize that with the address of the list_head. And then as they traverse the list, they can remove the entry without using any conditionals, by just doing

*pp = entry->next

有人能再解释一下为什么这种方法更好,以及它如何在没有条件语句的情况下工作吗?

推荐答案

一开始,你需要做的就是

pp = &list_head;

并且,当您遍历列表时,您可以用

pp = &(*pp)->next;

这样,您就可以始终跟踪"您来自"的点,并可以修改住在那里的指针.

因此,当你发现要删除的条目时,你只需

*pp = entry->next

这样,您就处理了另一个答案中Afaq个提及的所有3个 case ,有效地消除了对prevNULL判断.

C++相关问答推荐

C中char数组指针的问题

变量的const视图是否定义良好?

当我运行/调试C程序时,Malloc()似乎正在将&q;r\r...&q;赋值给一个指针,我不确定为什么?

Linux不想运行编译后的文件

函数内的局部字符指针

Sizeof(&Q;字符串&Q;)的正确输出是什么?

Flose()在Docker容器中抛出段错误

防止C++中递归函数使用堆栈内存

ifdef __cplusplus中的整数文字单引号

如何在GET_STRING输入后对少数几个特定字符串进行C判断?

如何在C++中安全地进行浮点运算

我在反转双向链表时遇到问题

是否定义了此函数的行为?

安全倒计时循环

为什么WcrTomb只支持ASCII?

如何使这个While循环在新行上结束

如何在C中定义指向函数的指针并将该指针赋给函数?

函数的typedef是标准 C 语法吗?它与函数指针的typedef有何不同?

Struct 内的数组赋值

Linux memcpy 限制关键字语法