【发布时间】:2017-01-19 06:49:41
【问题描述】:
我想比较p、p + 1、q和q + 1的内存地址和指针值。
我想了解以下值的实际含义。我无法完全理解发生了什么。
当我运行代码时:
- 每次我将地址
p与另一个指针进行比较时,我都会得到00EFF680的答案。 - 每次我将
q的地址与另一个指针进行比较时,我都会得到00EFF670的答案。 - 当我查看
p的指针值时,我得到了15726208的答案。 当我查看
p + 1的指针值时,我得到了15726212的答案。当我查看
q的指针值时,我得到了15726192的答案- 我得到了
15726200的答案,我查看了q + 1的指针值。
代码
#include <iostream>
#include <string>
using namespace std;
int main()
{
int val = 20;
double valD = 20;
int *p = &val;
double *q;
q = &valD;
cout << "Memory Address" << endl;
cout << p == p + 1;
cout << endl;
cout << q == q + 1;
cout << endl;
cout << p == q;
cout << endl;
cout << q == p;
cout << endl;
cout << p == q + 1;
cout << endl;
cout << q == p + 1;
cout << endl;
cout << "Now Compare Pointer Value" << endl;
cout << (unsigned long)(p) << endl;
cout << (unsigned long) (p + 1) << endl;
cout << (unsigned long)(q) << endl;
cout << (unsigned long) (q + 1) << endl;
cout <<"--------" << endl;
return 0;
}
【问题讨论】:
-
运算符优先级。
-
你的确切问题是什么?
-
您机器上的
integers 是 4 字节长,这就是为什么p和p + 1指针之间有 4 个字节的差异,而doubles 是 8 字节长. -
如果你有一个
type和一个指向它的指针,比如type* pointer;,这个表达式将(几乎)总是正确的:((pointer + 1) - pointer) == sizeof(type)。 -
@Jezor 我想比较 p、p +1 、q 和 q + 1。并了解结果的含义。
标签: c++