Lavakusa
Lavakusa

Reputation: 115

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.

Upvotes: 2

Views: 239

Answers (4)

Killzone Kid
Killzone Kid

Reputation: 6240

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

Upvotes: 5

Aakash Deep
Aakash Deep

Reputation: 114

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

Upvotes: 8

S_Madankar
S_Madankar

Reputation: 79

I will explain the logic in the form of comments in following code:

#include <iostream>
using namespace std;
int main()
{
  int t[4] = { 8, 4, 2, 1 };
  int *p1 = t + 2, *p2 = p1 - 1; /* p1 will point to 3rd element of array i.e. t[2]=2 and p2 will point to 2nd element i.e. t[1]=4 */
  p1++; // now p1 will point to 4th element i.e t[3]=1 
  cout << *p1 - t[p1 - p2] << endl; /* So 1-t[2] = 1 - 2 = -1 Since array difference is return in terms of Number of element which can be occupied in that memory space . So, instead of returning 8 , p1-p2 will give 2 */ 
  return 0;
}

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234775

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).

Upvotes: 5

Related Questions