问题
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;
}
the pointer a is not updating and still retains its old value inside the function update
回答1:
a is a copy of the pointer that was passed. At the end of update, a is lost. When you do this:
a = &temp3;
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;
}
回答2:
Simple answer is because in a = &temp3; you're assigning an memory address of parameter temp3 which is probably in a function stack call, to *a parameter of function which also is laying on the function stack call.
来源:https://stackoverflow.com/questions/60296699/pointer-not-updating-the-value-it-is-pointing-to-inside-void-function