以下是我编写的代码片段,目前正在努力打印输出。
在我的主要方法中,我使用有效输入调用函数 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
) .此外,不要忘记释放您动态分配的任何内存:任何使用 malloc
、calloc
或 realloc
分配的内存必须稍后使用 免费
。
我是一名优秀的程序员,十分优秀!