【问题标题】:What is the logic behind the below program?以下程序背后的逻辑是什么?
【发布时间】:2018-06-18 09:00:15
【问题描述】:
#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 

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

【问题讨论】:

  • 指针算法考虑了指针类型。
  • @Bathsheba@Aakash Deep@Killzone Kid@S_Madankar。非常感谢..
  • Protips (1) 所以只允许你标记一个人。是我,因为我是第一个。 (2) 如果答案告诉了你你想知道的,你应该接受。

标签: c++ c++11 visual-c++ visual-studio-2015


【解决方案1】:

您的cout 相当于

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

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

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

p1 - p2 在评估点是 (t + 3) - (t + 1),即 2。请注意,指针算术以 sizeof 您的类型为单位,不是 1。这说明了地址是sizeof(int) 的倍数。

【讨论】:

  • “请注意,指针算术是以你的类型的大小为单位,而不是 1”:在我看来,这是你答案中最重要的部分。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    请查看 cmets 以获取解决方案

    #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

    【讨论】:

    • 投个赞成票,这是回答这个问题的好方法。
    【解决方案4】:

    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

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

    【讨论】:

      猜你喜欢
      • 2020-05-22
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 2017-10-17
      • 1970-01-01
      • 1970-01-01
      • 2015-07-31
      相关资源
      最近更新 更多