首页 > 解决方案 > 为什么在这个程序中使用指针而不是常规变量?

问题描述

谁能解释一下这段代码是如何工作的?指针有点令人困惑,所以我需要一点帮助来了解正在发生的事情。我知道它正在计算总和和绝对差,但我不明白为什么我们需要这里的指针。请帮忙。

#include <iostream>

using namespace std;

void update(int *a, int *b) {    
   int sum = *a + *b;
   int abs = *a - *b;
   if (abs < 0) abs *= -1;
   cout << sum << '\n' << abs;
}

int main() {
   int a, b;
   int *pa = &a, *pb = &b;
   cin >> a >> b;
   update(pa, pb);
   return 0;
}

标签: c++pointers

解决方案


I don't get why we need pointers here

We don't. This piece of code is needlessly convoluted. My best guess is your teacher is building up to something they haven't shown you yet.

The use of pointers here is pointless. No pun intended. You could do exactly the same thing without pointers.

That doesn't mean pointers are useless. They are very important. But that piece of code is just... not suited to show their importance.


推荐阅读