我正在做一项编程作业,但在使用指针时遇到了一些问题。下面的代码示例不是我的作业,而是说明我遇到的问题。我试图将指向一个对象的指针传递给另一个函数(从 change 到 really)并让该函数创建一个新对象然后返回它。但是,我发现原始对象并没有真正改变。我不明白为什么不,因为我使用 malloc 在堆上分配它,所以对象应该在创建它的函数之外持续存在。
在下面的代码示例中,我正在寻找输出:
a = 3
a = 5
但是我得到了
a = 3
a = 3
即使只是一些正确方向的指示也会很有用!谢谢!
山姆
注意事项
- 如果可能的话,我希望保持函数原型(prototype)相同。
示例代码
#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;
}
最佳答案
C 只支持按值传递
。当您将指针传递给函数时,指针的值(即它指向的地址)被复制到函数参数,一个新变量。
在函数 really()
中,您已经用 b
指向的地址覆盖了新指针 a
存储的地址。所以,这不会反射(reflect)在 main()
中。但是,如果您取消引用 a
并为其分配新值 5
,则 main()
中 a
的值也会改变。
关于c - 将指针传递给函数并更改它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22425559/