c++ - 指针不更新它在 void 函数内指向的值

标签 c++ pointers

我做了一个简单的函数,简单地使用指针进行参数之间的加法和绝对差,但是当我尝试更新指针时,指针仍然具有旧值。为什么会这样,或者我做错了什么:

#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/

相关文章:

c - malloc() 和 calloc() 是否正确?

c++ - 是否有可能在 C++ 中的 std::vector<char> 中获取连续内存片段的指针?

c++ - 我想要的自动生成文件

c++ - 指针和带分配内存的指针有什么区别?

c - c中的指针类型

c++ - 使用 NEAT C++ 实现自定义 AI

c - 为什么这个对象在函数调用后没有被设置为 NULL?

c++ - 即使在子弹模式下也能穿透物体

c++ - CMake如何处理QtCreator中的对象依赖(.o.d)

c++ - 警告从 `int' 转换为 `double'