我做了一个简单的函数,简单地使用指针进行参数之间的加法和绝对差,但是当我尝试更新指针时,指针仍然具有旧值。为什么会这样,或者我做错了什么:
#include <stdio.h>
#include <cstdlib>
void update(int *a,int *b) {
int temp = *a;
int temp2 = *b;
int temp3 =0;
temp3 = temp + temp2;
printf("%d",temp3);
*b = abs(*a - *b);
a = &temp3; // it is not updating
}
int main() {
int a, b;
int *pa = &a, *pb = &b;
scanf("%d %d", &a, &b);
update(pa, pb);
printf("%d\n%d", a, b);
return 0;
}
指针 a 没有更新,并且在函数 update 中仍然保留其旧值
最佳答案
a
是所传递的指针的拷贝。在update
结束时,a
丢失。当你这样做时:
a = &temp3;
您更改了 a
的值,但这并不重要,因为 a
无论如何都会消失。相反,将值分配给它指向的位置,就像您对 b
所做的那样:
*a = temp3;
您还可以使用引用代替指针:
void update(int &a, int &b) {
int temp = a;
int temp2 = b;
int temp3 = temp + temp2;
printf("%d ", temp3);
b = abs(a - b);
a = temp3;
}
int main() {
int a, b;
scanf("%d %d", &a, &b);
update(a, b);
printf("%d\n%d", a, b);
return 0;
}
关于c++ - 指针不更新它在 void 函数内指向的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60296699/