Q:

What is the logic behind the below program?

#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;
}

here p1 = 0x00000007c2affa24[1] 
p2 = 0x00000007c2affa1c[4] (address and value) but p1-p2 = 2
output is -1 

I am not able to understand this logic, Please help me. 

A:

Please look through the comments for solution    
#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;
}

Have a look to this website
https://www.tutorialspoint.com/cprogramming/c_pointer_arithmetic.htm

A:

Your cout is equivalent to
std::cout << t[3] - t[2] << endl;.
Furthermore t[3] - t[2] is -1.
p1 starts off as t + 2, and p1++ increments it to t + 3. So *p1 is t[3] at the point of calling std::cout.
p1 - p2 is (t + 3) - (t + 1) at the point of evaluation which is 2. Note that pointer arithmetic is in units of sizeof your type, not 1. That accounts for the difference in the addresses being a multiple of the sizeof(int).

A:

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

{ 8, 4, 2, 1 }
  ^
  t

int *p1 = t + 2;

{ 8, 4, 2, 1 }
        ^
        p1

int *p2 = p1 - 1;

{ 8, 4, 2, 1 }
     ^  ^
     p2 p1

p1++;

{ 8, 4, 2, 1 }
     ^     ^
     p2    p1

(p1 - p2 => 2)

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

1 - t[2] => 1 - 2 => -1

