【问题标题】:pointer not updating the value it is pointing to inside void function指针不更新它在 void 函数中指向的值
【发布时间】:2020-02-19 09:16:03
【问题描述】:

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

#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 中保留它的旧值

【问题讨论】:

  • 请记住,默认情况下,C++ 中的函数参数是按值传递的,即值被复制到参数变量中。因此,当您修改 a 时,您修改的是副本,而不是原始值(来自 main 函数的 pa 的值)。
  • 此外,您尝试做的是让a 指向update 函数内的local 变量。局部变量的生命周期在函数结束时结束,这样的指针会立即失效。

标签: c++ pointers


【解决方案1】:

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;
}

【讨论】:

    【解决方案2】:

    简单的答案是因为在a = &amp;temp3; 中,您将可能在函数堆栈调用中的参数 temp3 的内存地址分配给函数的 *a 参数,该参数也位于函数堆栈调用上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 2013-07-19
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      • 2016-03-20
      • 1970-01-01
      相关资源
      最近更新 更多