以下程序背后的逻辑是什么?

Lav*_*usa 2 c++ visual-c++ c++11 visual-studio-2015

#include <iostream>
using namespace std;
int main()
{
  int t[4] = { 8, 4, 2, 1 };
  int *p1 = t + 2, *p2 = p1 - 1;
  p1++; 
  cout << *p1 - t[p1 - p2] << endl;
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这里p1 = 0x00000007c2affa24 [ 1 ] p2 = 0x00000007c2affa1c [ 4 ](地址和值)但p1-p2 = 2

output is -1 
Run Code Online (Sandbox Code Playgroud)

我无法理解这个逻辑,请帮助我.

小智 8

请仔细阅读解决方案的评论

#include <iostream>
using namespace std;
int main()
{
  int t[4] = { 8, 4, 2, 1 };

  int *p1 = t + 2, *p2 = p1 - 1;  
  // p1 holds the address of t[2],  p2 holds the address of t[1]  

  p1++;   
  //Now, p1 holds the address of t[3]  

  cout << *p1 - t[p1 - p2] << endl;  // We need to pointer arithmetic  
  //Here p1 has the value 1,
  //t[(t+3)-(t+1)] = t[2] which is 2,
  //So, the answer would be 1-2 = -1
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

看看这个网站 https://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htm

  • 有一个upvote,这是回答这个问题的一个很好的明确方式. (2认同)

Bat*_*eba 5

cout的等同于

std::cout << t[3] - t[2] << endl;.

而且t[3] - t[2]-1.

p1从as开始t + 2,并将p1++其增加到t + 3.所以*p1就是t[3]打电话std::cout.

p1 - p2(t + 3) - (t + 1)在评价点,这是2.注意,指针运算的单位sizeof的类型,不是 1.即占该地址为的倍数的差别sizeof(int).


Kil*_*Kid 5

int t [4] = {8,4,2,1};

{ 8, 4, 2, 1 }
  ^
  t
Run Code Online (Sandbox Code Playgroud)

int*p1 = t + 2;

{ 8, 4, 2, 1 }
        ^
        p1
Run Code Online (Sandbox Code Playgroud)

int*p2 = p1 - 1;

{ 8, 4, 2, 1 }
     ^  ^
     p2 p1
Run Code Online (Sandbox Code Playgroud)

P1 ++;

{ 8, 4, 2, 1 }
     ^     ^
     p2    p1
Run Code Online (Sandbox Code Playgroud)

(p1 - p2 => 2)

cout <<*p1 - t [p1 - p2] << endl;

1 - t[2] => 1 - 2 => -1
Run Code Online (Sandbox Code Playgroud)