首页 > 解决方案 > Operations with pointers in linked lists

问题描述

Generally, I know that a pointer stores the memory address of another value located in computer memory, for example:

int firstvalue= 5
int * p1;
p1 = &firstvalue;  // p1 = address of firstvalue

What happens if we define an operation like the following in a linked list? Does *current=*list means that the value pointed to by current equals to the value pointed to by list? And what does it mean if we define ecur=current?

int function(struct list_t **list){
    struct list_t *ecur=NULL;
    struct list_t *current=*list;
    ecur=current;
}

Update: What does it do *list=remove(*list, param1, param2)? And why is that?

remove is a function that returns a modified list of list.

Update 2: Why do we need to define a pointer to pointer in order to modify the list? Is *list a pointer to pointer?

标签: cpointerslinked-list

解决方案


该变量list是一个指向结构 list_t 的指针的指针。如果我们(仅作为示例)假设该结构位于地址 2000 并且未命名指针位于地址 1000 它将如下所示:

在此处输入图像描述

然后你有添加两个新变量的初始化。两者都作为指向 struct list_t 的指针。

struct list_t *ecur=NULL;
struct list_t *current=*list;

所以现在图片变成了:

在此处输入图像描述

请注意,current它与中间的“some-pointer”具有相同的值,因为它*list被分配给current.

然后你有任务:

ecur=current;

这意味着ecur获得与图片相同的值current并给出图片:

在此处输入图像描述

更新:它有什么作用*list=remove(*list, param1, param2)

它改变了图片中间的“一些指针”的值。例如,如果remove函数删除链表中的第一个元素,则需要这样做。


推荐阅读