c++ - 为什么在这个程序中使用指针而不是常规变量?
问题描述
谁能解释一下这段代码是如何工作的?指针有点令人困惑,所以我需要一点帮助来了解正在发生的事情。我知道它正在计算总和和绝对差,但我不明白为什么我们需要这里的指针。请帮忙。
#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;
}
解决方案
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.
推荐阅读
- r - 验证日期序列的顺序是否正确
- kubernetes - 我正在尝试将 externalname 与 Nginx-Controller 的 nodeport 服务一起使用,但我得到 502 Bad Gateway
- ios - 如何更改 UISearchBar 的边框粗细?
- python - python程序读取json文件中的特定字段输出错误
- c - 将文本文件转换为 CSV 文件的 C 程序
- django - Django DRF 在错误消息中显示字段的详细名称
- php - 对多维数组进行多级排序
- java - 目标 org.codehaus.mojo:exec-maven-plugin:1.6.0:java 的参数“mainClass”丢失或无效
- python - 使用查询集搜索后 Django 重定向
- ios - 从firebase存储返回的url是nil Swift4