pointer not updating the value it is pointing to inside void function

烂漫一生 提交于 2021-01-28 05:26:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!