gpt4 book ai didi

c - 我不明白指针、地址和范围

转载 作者:太空宇宙 更新时间:2023-11-04 05:05:06 27 4
gpt4 key购买 nike

以下是我编写的代码片段,目前正在努力打印输出。

在我的主要方法中,我使用有效输入调用函数 insertPoint 两次,例如:insertPoint(42); insertPoint(56); 并获得以下输出:

A.1 42
B.3 2686700

但是在 B.3 中,我希望它也返回值 42,但它没有。我假设 2686700 指的是内存中的某个地址。

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

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

struct point *root;

int insertPoint(int value) {
// Graph is empty, set new root
if(root == 0){
struct point newRoot;
newRoot.value = value;

root = &newRoot;
(*root).value = value;
printf("A.1 %d \n", (*root).value); // "A.1 42"
return value;
}
printf("B.3 %d \n", (*root).value); // "B.3 2686700"

/* rest of code here; irrelevant since related variables are not changed */
}

有人知道为什么会这样吗?任何建设性的评论/答案表示赞赏。

我也很感激,如果反对者能给我反馈,为什么他们觉得我的问题不合适。

最佳答案

如果采用if (root == 0)分支,root将指向struct point newRoot;堆栈在 if 分支的主体内。 newRoot 结构在离开分支主体和函数主体后超出范围,在您的例子中是在 return value; 语句之后。但是,全局指针变量 root 将一直指向内存中的那个位置(在堆栈上)。该位置的堆栈内存内容很可能会被其他代码覆盖,因此从该位置读取 point(成员)值(例如通过 root 指针)将导致未定义的行为,这就是为什么你会得到这样的结果。

您可能打算动态分配新根,例如:

if(root == 0) {
root = (point *) malloc(sizeof(point));
root->value = value;
root->next = NULL;
printf("A.1 %d \n", root->value); // "A.1 42"
return value;
}

不要忘记设置 next 指针,因为默认情况下它不会是 NULL(除非您使用 malloc calloc 对返回的内存进行零初始化,有效地使 next 的值在大多数平台上等于NULL) .此外,不要忘记释放您动态分配的任何内存:任何使用 malloccallocrealloc 分配的内存必须稍后使用 免费

关于c - 我不明白指针、地址和范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36822164/

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