为什么在使用指针时不能使用“++”来增加 int 变量的值?

Why can I not increment the value of an int variable by using "++" when working with pointers?

我正在尝试使用存储该元素地址的指针来增加数组中元素的值。

当我把它写成“p++;”时它不起作用,而如果我把它写成*p=*p+1它就起作用了。

*p=*p+1; // this increments the value
*p++; //while this does not

我希望这两种方式都能奏效

operator ++ 比解除引用具有更高的优先级,因此 *p++ 递增指针然后执行解除引用。如果你想增加它最初指向的值,那么你需要添加括号:(*p)++;

#include <iostream>
using namespace std;

int main (int argc, char *argv[])
{
  int numbers[] = { 100, 200, 300, 400, 500, 600 };
  int *p1 = &numbers[0];
  int *p2 = &numbers[2];
  int *p3 = &numbers[4];
  *p1 = *p1 + 1;
  *p2 = *p2++;
  ++*p3;
  cout << numbers[0] << " " << numbers[1]  << " " << numbers[2] << " " <<  numbers[3] << " " <<  numbers[4] << " " <<  numbers[5];
}

运行 通过 Xcode 这让我知道出了什么问题,它说:"temp/test.cxx:11:12: warning: unsequenced modification and access to 'p2' [-Wunsequenced]".

输出为101 200 300 300 501 600

正如你在问题中所说,第一种方法有效。

第二个做的事情与您的预期完全不同:它获取 p2 (300) 指向的值,然后递增指针并将该值保存回新地址。

我认为 p3 的第三个示例更接近您想要实现的目标。