以下程序背后的逻辑是什么
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;
}
这里 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
。
p1
以 t + 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;
}
相关文章:
- "std::unique_XXX"命名约定背后的基本原理是什么?
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- while(sline >> n >> c && c== ',')背后的逻辑是什么?
- 有人能解释一下这些说法背后的逻辑是什么吗
- 在C++中为零大小的分配返回唯一地址背后的基本原理是什么?
- libc++ 的 std::basic_string 的 16 字节对齐模式背后的原因是什么?
- 不允许功能模板的部分专业化背后的理由是什么?
- 在查找子集中元素和元素数量之间的二进制比较背后的逻辑是什么?
- 不同向量启动作为类成员与方法中不同的矢量启动背后的原因是什么?
- typeid 运算符忽略 cv 限定符背后的理由是什么?
- 对于类型是类模板专业化的参数,ADL背后的理由是什么
- 模板类型背后的意义是什么?
- 以下程序背后的逻辑是什么
- 此代码中 * 1233 >> 12 计算十进制数字背后的数学原理是什么
- 当编译器看到 std::vector<Typo> 和 std::vector<struct 拼写错误时发出的诊断之间的差异背后的理由是什么>
- std::optional背后的基本原理是什么?
- 类实例和指针背后的Delphi设计原则是什么
- int64_t背后的魔力是什么
- C++中"using"关键字背后的逻辑是什么?
- "inline function need to be DEFINED in all tranlation units"背后的理由是什么?