gpt4 book ai didi

c++ - 在堆上创建的变量,指向同一个变量的2个指针有不同的地址?

转载 作者:太空狗 更新时间:2023-10-29 20:31:26 25 4
gpt4 key购买 nike

刚学了栈和堆的区别。在创建一个将为我在堆上动态分配内存的函数后,我返回指针并显示(在函数内和函数外)每个指针的地址和值。

值是相同的,这是我所期望的,但是堆上同一 block 内存的地址是不同的,这是我没有想到的。

为什么? pHeap2 和 pTemp 不应该指向同一个地址吗?

#include <iostream>
using namespace std;

int* intOnHeap(); // returns an int on the heap
int main()
{
int* pHeap = new int; // new operator allocates memory on the heap and returns its address
// 'new int' allocates enough memory on heap for one int and returns the address on the heap for that chunk of memory
// 'int* pHeap' is a local pointer which points to the newly allocated chunk of memory
*pHeap = 10;
cout << "*pHeap: " << *pHeap << "\n\n";

int* pHeap2 = intOnHeap();
cout << "pHeap2:\n-----------" << endl;
cout << "Address:\t" << &pHeap2 << "\n";
cout << "Value:\t\t" << *pHeap2 << "\n\n";

cout << "Freeing memory pointed to by pHeap.\n\n";
delete pHeap;

cout << "Freeing memory pointed to by pHeap2.\n\n";
delete pHeap2;

// get rid of dangling pointers
pHeap = 0;
pHeap2 = 0;

system("pause");
return 0;
}

int* intOnHeap()
{
int* pTemp = new int(20);
cout << "pTemp:\n-----------" << endl;
cout << "Address:\t" << &pTemp << "\n";
cout << "Value:\t\t" << *pTemp << "\n\n";
return pTemp;
}

输出:

*pHeap: 10

pTemp:
-----------
Address: 0042FBB0
Value: 20

pHeap2:
-----------
Address: 0042FCB4
Value: 20

Freeing memory pointed to by pHeap.

Freeing memory pointed to by pHeap2.

Press any key to continue . . .

最佳答案

您报告的是指针的地址,而不是指针指向的地址。当然,pTemppHeap2 的指针地址会有所不同;这些是恰好指向内存中相同地址的不同指针。删除 & 前缀 pTemppHeap2 以查看您期望的结果。

图片是这样的:

0042FBB0           0042FBC0     0042FCB4
------------ ------ ------------
| 0042FBC0 |------>| 20 |<------| 0042FBC0 |
------------ ------ ------------
pTemp pHeap2

此处 &pTemp0042FBB0&pHeap20042FCB4。我为 pTemppHeap2 指向的地址创建了一个地址(当然,结果可能因运行而异)并且如果您删除 & 前缀 pTemppHeap2 然后你会看到 0042FBC0 在每种情况下打印出来。

关于c++ - 在堆上创建的变量,指向同一个变量的2个指针有不同的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4295346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com