gpt4 book ai didi

c - 链表中指针指针的奇怪行为

转载 作者:太空宇宙 更新时间:2023-11-04 02:21:08 24 4
gpt4 key购买 nike

让我们考虑以下代码:

#include <stdio.h>
#include <stdlib.h>

struct NODE {
int value;
struct NODE *next;
};

int prepend(struct NODE **head, int n){
struct NODE *new_node = (struct NODE *)malloc(sizeof(struct NODE));
if (!new_node) return -1;
new_node->value = n;
new_node->next = *head;
*head = new_node;
return 0;
}

void pointer_address(struct NODE *head) {
struct NODE **p_current = &head;
struct NODE *next = NULL;
while (*p_current) {
printf("%p\n", (*p_current));
next = (**p_current).next;
printf("%p\n\n", (*p_current));
p_current = &(next);
}
}

void delete_list(struct NODE *head) {
struct NODE *current = head;
struct NODE *next = NULL;
while (current) {
next = current->next;
free(current);
current = next;
}
}

int main() {
struct NODE *head = NULL;
for(size_t i = 1; i < 10; i++) {
if (prepend(&head, i)) {
perror("Somenthing went wrong!\n");
return -1;
}
}
pointer_address(head);
delete_list(head);
}

在实践中,我创建了一个链表,并在其中添加了一些整数值。然而我无法理解的是函数“pointer_address”的输出。特别是我得到

0x55871ac39360
0x55871ac39360

0x55871ac39340
0x55871ac39320

0x55871ac39320
0x55871ac39300

0x55871ac39300
0x55871ac392e0

0x55871ac392e0
0x55871ac392c0

0x55871ac392c0
0x55871ac392a0

0x55871ac392a0
0x55871ac39280

0x55871ac39280
0x55871ac39260

0x55871ac39260
(nil)

当然,每次运行程序的特定值都是不同的。然而,我真正无法理解的是,为什么从第二对行开始,每对打印的值都不同。它们是

的结果
printf("%p\n", (*p_current)); 

在这两种情况下。此外,我注意到从第三对行开始,上面一行等于前一对的最后一行。

问题

这是怎么回事?

免责声明

我知道这段代码没有做任何有趣的事情,同样的事情可以用其他方式完成。然而,我的兴趣是了解我的代码发生了什么。

最佳答案

您的pointer_address 函数:

void pointer_address(struct NODE *head) {
struct NODE **p_current = &head;
struct NODE *next = NULL;
while (*p_current) {
printf("%p\n", (*p_current));
next = (**p_current).next;
printf("%p\n\n", (*p_current));
p_current = &(next);
}
}

产生奇怪结果的行是:

p_current = &(next);

这意味着当您更改 next 的值时,*p_current 的值也会更改,因为它们引用相同的内存。因此,您的 printf 语句之间的行更改了 *p_current 的值:

next = (**p_current).next;

此函数的更明智的实现不会使用指向指针的指针,只需要一个指针即可:

void pointer_address(struct NODE *head) {
struct NODE *p_current = head;
struct NODE *next = NULL;
while (p_current) {
printf("%p\n", p_current);
next = p_current->next;
printf("%p\n\n", p_current);
p_current = next;
}
}

或者进一步简化:

void pointer_address(struct NODE *p_current) {
while (p_current) {
printf("%p\n", p_current);
p_current = p_current->next;
}
}

关于c - 链表中指针指针的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58050231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com