一篇关于指针的CSDN文章居然没看懂
本帖最后由 bluelion9527888 于 2013-01-15 17:13:55 编辑 对话Linus Torvalds:大多黑客甚至连指针都未理解
http://www.csdn.net/article/2013-01-10/2813559-two-star-programming
“不懂指针”的开发者代码示例:
typedef struct node
{
struct node * next;
....
} node;
typedef bool (* remove_fn)(node const * v);
// Remove all nodes from the supplied list for which the
// supplied remove function returns true.
// Returns the new head of the list.
node * remove_if(node * head, remove_fn rm)
{
for (node * prev = NULL, * curr = head; curr != NULL; )
{
node * next = curr->next;
if (rm(curr))
{
if (prev)
prev->next = curr->next;
else
head = curr->next;
free(curr);
}
else
prev = curr;
curr = next;
}
return head;
}
void remove_if(node ** head, remove_fn rm)
{
for (node** curr = head; *curr; )
{
node * entry = *curr;
if (rm(entry))
{
*curr = entry->next;
free(entry);
}
else
curr = &entry->next;
}
}
rm是指是否删除这个元素。 *curr = entry->next; 这句就是越过了*curr指向的元素,让*curr指下entry的下一个元素entry->next...因为是2维指针,所以修改了前一个结点的next域值。
当不用删除时,curr = &entry->next只是将curr移到后一个元素上。
链表,画个图就知道了。