【发布时间】:2021-04-08 01:06:29
【问题描述】:
我有以下代码:
#include <iostream>
using namespace std;
int main()
{
int i, j;
int *p = &i;
cout << "Address of i = " << &i << endl;
cout << "Address of j = " << &j << ", which is " << &i - 1 << endl;
cout << "Address of p = " << &p << ", which is NOT " << &j - 1 << endl;
}
我得到了以下输出(VS Code,带有 GCC):
Address of i = 0x61fe1c
Address of j = 0x61fe18, which is 0x61fe18
Address of p = 0x61fe10, which is NOT 0x61fe14
我认为局部变量,如 int 或指针,是在堆栈中连续分配的。所以我期待
Address of i = 0x61fe1c
Address of j = 0x61fe18
Address of p = 0x61fe14
我在这里错过了什么?
编辑:我想我明白了。指针指向变量的低地址。
#include <iostream>
using namespace std;
int main()
{
int i, j;
int *p;
int k, x;
cout << "Address of i = " << &i << endl;
cout << "Address of j = " << &j << ", which is " << &p + 1 << endl;
cout << "Address of p = " << &p << ", which is " << &k + 1 << endl;
cout << "Address of k = " << &k << ", which is " << &x + 1 << endl;
}
这给了我
Address of i = 0x61fe1c
Address of j = 0x61fe18, which is 0x61fe18
Address of p = 0x61fe10, which is 0x61fe10
Address of k = 0x61fe0c, which is 0x61fe0c
正如预期的那样。
【问题讨论】:
-
存储变量的实际内存地址是否对您很重要?
-
这里有一个提示:在您的机器上,
sizeof(int) == 4和sizeof(int*) == 8 -
我认为局部变量,如 int 或指针,是在堆栈中连续分配的 -- 你从哪里得到这个(错误的)信息?
-
我认为执行
&i - 1和&j - 1是未定义的行为。对于手头的讨论和这个小程序可能并不重要。但不应该进入生产代码。 -
栈本身是连续的。但是编译器可以没有义务将你声明的变量以特定的顺序放入堆栈。
标签: c++