指针不更新它在 void 函数内部指向的值 [英] pointer not updating the value it is pointing to inside void function
问题描述
我制作了一个简单的函数,它使用指针对参数之间的加法和绝对差异进行了简单的处理,但是当我尝试更新指针时,指针仍然具有旧值.为什么会这样,或者我做错了什么:
I've made a simple function that simple does the addition and absolute difference between the parameters using pointers, but when I try to update the pointer, the pointer still has the old value. why is this so, or what am I doing wrong:
#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 中的旧值
the pointer a is not updating and still retains its old value inside the function update
推荐答案
a
是传递的指针的副本.update
结束时,a
丢失.当你这样做时:
a
is a copy of the pointer that was passed. At the end of update
, a
is lost. When you do this:
a = &temp3;
您更改了 a
的值,但这并不重要,因为无论如何 a
已经消失了.相反,将值分配给它指向的位置,就像您对 b
所做的一样:
You change the value of a
, but that doesn't matter, because a
is gone after that anyway. Instead, assign the value to where it's pointing at, much like you did with b
:
*a = temp3;
你也可以使用引用代替指针:
You could also use references instead of pointers:
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;
}
这篇关于指针不更新它在 void 函数内部指向的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!