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

时间:2018-01-09 10:36:48

标签: c++ c++11 visual-c++ 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;
}

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

output is -1 

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

4 个答案:

答案 0 :(得分:8)

请查看解决方案的评论

pom.xml

浏览本网站 coap.IncomingMessage

答案 1 :(得分:5)

您的cout相当于

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

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

p1t + 2开头,p1++将其增加为t + 3。因此*p1在调用t[3]时是std::cout

p1 - p2在评估点(t + 3) - (t + 1)为2.请注意,指针算术的类型为sizeof 1。将地址差异视为sizeof(int)的倍数。

答案 2 :(得分:5)

  

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 =&gt; 2

  

cout&lt;&lt; * p1-t [p1-p2]&lt;&lt; ENDL;

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

答案 3 :(得分:2)

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

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