【发布时间】:2014-03-15 15:13:45
【问题描述】:
我正在处理一项编程任务,但我的指针出现了一些问题。下面的代码示例不是来自我的家庭作业,而是说明了我遇到的问题。我正在尝试将指向对象的指针传递给另一个函数(从更改到真正)并让该函数创建一个新对象然后返回它。但是,我发现原始对象并没有真正改变。我不知道为什么不这样做,因为我使用 malloc 在堆上分配它,所以对象应该在创建它的函数之外持续存在。
在下面的代码示例中,我正在寻找输出:
a = 3
a = 5
但是我得到了
a = 3
a = 3
即使只是一些正确方向的指针也会很有用!谢谢!
山姆
备注
- 我希望尽可能保持函数原型相同。
示例代码
#include <stdio.h>
#include <stdlib.h>
void really(int *a) {
/* Allocate pointer to new int, set it to 5, and
then set the pointer passed in equal to the new pointer */
int *b = malloc(sizeof(int));
*b = 5;
a = b;
}
void change(int *a) {
/* We don't actually change the object in this function;
we are instead passing it to a different function to change */
really(a);
}
int main() {
int a = 3;
printf("a = %d\n", a);
change(&a);
printf("a = %d\n", a);
return 0;
}
【问题讨论】:
-
无需在每个
void函数的末尾添加return;。 -
@pzaenger 我已经删除了 void 函数末尾的 return 语句。
-
无需添加正确的代码。可以简单地查看接受的答案。
-
好的;我已经删除了它。谢谢!