c++ - 为什么在 cpp/c 中使用指针引用时自增运算符 (++) 不起作用
问题描述
我正在编写与 C/C++ 中的引用相关的代码。我做了一个指针并将它放入一个递增它的函数中。在函数中,我编写*ptr++
并尝试增加指针指向的整数的值。
#include <iostream>
using namespace std;
void increment(int *ptr)
{
int &ref = *ptr;
*ptr++; // gets ignored?
ref++;
}
int main()
{
int a = 5;
increment(&a);
cout << a;
return 0;
}
谁能告诉我为什么我不能增加变量?我尝试使用 增加它+=1
,它可以工作,但不能使用++
运算符?
解决方案
++
优先级高于*
,因此*ptr++
被视为*(ptr++)
。这增加了指针,而不是它指向的数字。
要增加数字,请使用(*ptr)++
。
推荐阅读
- vba - VBA-复制所有数据而不是重复数据
- reactjs - 如何使用 ComponentDidMount 呈现值以形成反应
- powerbi - 需要将当前月份与过去 3 个月的平均值进行比较
- django - 如何在 Django 2.1 中包含 DRF 3.8 路由器 url 模式
- kotlin - 如何根据传入参数向 Exposed DAO API“.find”添加多个过滤条件
- javascript - 来自两个数组(Javascrip / Typescript)的元素组合的逻辑
- php - 如何在laravel中添加碳中的差异
- laravel - 我如何通过 laravel 找到 long 和 lat 附近的地方
- php - Textarea $_POST 没有返回值
- php - Magento 2 如何将自定义属性添加到发票电子邮件和发票 PDF