![](/img/trans.png)
[英]why increment variable changing the value of the array when they have different names
[英]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:警告:未進行順序的修改和對'p2'[-Wunsequenced]的訪問”。
輸出為101 200 300 300 501 600
。
正如您在問題中所說,第一種方法有效。
第二個所做的事情與您期望的完全不同:它采用p2所指向的值(300),然后遞增指針並將該值保存回該新地址。
我認為p3的第三個示例更接近您要實現的目標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.