指针算术增加后/预修复

73m*_*eam 2 c++ pointers pointer-arithmetic

我无法完成下面某段特定代码的逻辑.

int i[] = { 21, 4, -17, 45 };

int* i_ptr = i;

std::cout << (*i_ptr)++ << std::endl;   // 21

std::cout << *i_ptr << std::endl;       // 22

std::cout << *i_ptr++ << std::endl;     // 22

std::cout << *(i_ptr - 1) << std::endl; // 22

std::cout << *i_ptr << std::endl;       // 4

std::cout << ++*i_ptr << std::endl;     // 5

std::cout << *++i_ptr << std::endl;     // -17

system("pause");
Run Code Online (Sandbox Code Playgroud)

我的问题是这段代码是如何从22 ...

std::cout << *(i_ptr - 1) << std::endl; // 22
Run Code Online (Sandbox Code Playgroud)

到4.

std::cout << *i_ptr << std::endl;       // 4
Run Code Online (Sandbox Code Playgroud)

然后到5.

std::cout << ++*i_ptr << std::endl;     // 5
Run Code Online (Sandbox Code Playgroud)

当我第一次看到这段代码时,我认为22就是从22到21.我明白它与C++运算符优先级有关,但这对我来说毫无意义.

mch*_*mch 5

std::cout << (*i_ptr)++ << std::endl;   // 21
//i_ptr points to i[0], which is increased from 21 to 22

std::cout << *i_ptr << std::endl;       // 22
//prints i[0], which is 22

std::cout << *i_ptr++ << std::endl;     // 22
//prints i[0] and increments i_ptr to point to i[1]

std::cout << *(i_ptr - 1) << std::endl; // 22
//prints i[0], i_ptr points to i[1], so i_ptr - 1 points to i[0]

std::cout << *i_ptr << std::endl;       // 4
//prints i[1], which is 4

std::cout << ++*i_ptr << std::endl;     // 5
//prints the incremented i[1], which was 4 and is 5 now

std::cout << *++i_ptr << std::endl;     // -17
//increment i_ptr to point to i[2] and prints the value
Run Code Online (Sandbox Code Playgroud)