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

What is the logic behind the below program?

本文关键字:是什么 背后 程序      更新时间:2023-10-16
#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;
}

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

output is -1 

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

请查看评论以获取解决方案

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

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

您的cout相当于

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

此外,t[3] - t[2] -1

p1t + 2 开头,p1++将其递增为 t + 3 。所以*p1在打电话std::cout的时候t[3]了.

p1 - p2在评估点(即 2((t + 3) - (t + 1)。请注意,指针算术的单位是sizeof类型,而不是 1。这解释了地址的差异是sizeof(int)的倍数。

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

{ 8, 4, 2, 1 }
  ^
  t

整数 *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

我将在以下代码中以注释的形式解释逻辑:

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