我在C中使用指针有问题

我在C中使用指针有问题

本文介绍了我在C中使用指针有问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释此代码的工作原理.我尝试将其写出并环绕它,但是我仍然迷失了方向.

Could someone please explain to me how this code works. I tried writing it out and wrapping my head around it, but I am still lost.

设置next->prev = prev时,next->prev和prev之间的值有什么区别?它们的价值不一样吗?下一行也有同样的问题.

When you are setting next->prev = prev what is the difference in value between next->prev and prev? aren't they the same value? same question for the next line as well.

我试图写出ListElement结构来帮助理解,但我仍然感到困惑.任何答案或帮助,或任何其他可以使我理解的参考文献,将不胜感激.我是一个视觉学习者,所以如果您碰巧知道这一点,我将不胜感激.

I tried writing out a ListElement struct to try to help understand but I am still confused. Any answer or help would be greatly appreciated, or any other references that can make me understand. I am a visual learner so if you happen to know a good visualization of this, I would appreciate it.

int unlink(ListElement *element)
{
    ListElement *next = element->next;
    ListElement *prev = element->prev;

    next->prev = prev;
    prev->next = next;

    return 0;
}

推荐答案

前两个分配将连接" 定义到上一个 1和下一个 3节点.

The first two assignments define "connections" to the previous, 1, and next, 3, node.

ListElement *next = element->next;  // next connects current node to the one that follows
ListElement *prev = element->prev;  // prev connects current node to the one that precedes

这就是为什么它们被称为prev和next的原因.其他两行是 re-wiring prev和next节点,因此它们跳过了当前节点,即您正在通过上面定义的连接访问前后节点的成员:

that is why they are called prev and next. The other two lines are re-wiring the prev and next nodes such that they skip the current node, i.e.you are accessing the preceding and following nodes's members via the connections defined above:

next->prev = prev; // now node: 3 is connected to node: 1
prev->next = next; // now node: 1 is connected to node: 3


注意:请记住,每个节点都有两个名为prev和next

这篇关于我在C中使用指针有问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:50