代码如下:
int main()
{
using namespace std;
int nights = 1001;
int * pt = new int; // allocate space for an int
*pt = 1001; // store a value there
cout << "nights value = ";
cout << nights << ": location " << &nights << endl;
cout << "int ";
cout << "value = " << *pt << ": location = " << pt << endl;
double * pd = new double; // allocate space for a double
*pd = 10000001.0; // store a double there
cout << "double ";
cout << "value = " << *pd << ": location = " << pd << endl;
cout << "location of pointer pd: " << &pd << endl;
cout << "size of pt = " << sizeof(pt);
cout << ": size of *pt = " << sizeof(*pt) << endl;
cout << "size of pd = " << sizeof pd;
cout << ": size of *pd = " << sizeof(*pd) << endl;
return 0;
}
下面是作者对代码的注释:
Another point to note is that typically new uses a different block of memory than do the ordinary variable definitions that we have been using. Both the variable nights and pd have their values stored in a memory region called the stack, whereas the memory allocated by the new is in a region called the heap or free store.
最初的问题:
现在我担心的是:变量 pd 是由关键字 new 创建的,所以它应该存储在名为 heap 的区域中就像变量 pt 一样,因为它们都是由关键字 new 创建的。
我在这里遗漏了什么吗?非常感谢您的意见。
基于保留的修订问题/跟进:
This question was put on hold by 5 people because they couldn't understand what I was asking. I believe that my question has already been answered but for those who are still not sure about what I was initially asking please read along:
I was unclear about the author's explanation about where the variables and their values were stored in memory. Up to the author explanation, I had a belief that any memory created dynamically (or should I say during runtime after compiling) by using the keyword new gets stored in the heap not the stack.
So, it confused me when he wrote that the variable pd has is value stored in the stack, but again how is that possible if the variable was create during "runtime" with the keyword new, so it should be in the heap, not the stack.
请尝试使用上面的代码作为引用,尤其是您的答案中的**变量(nights、pd 和 pt),以便我可以从该代码的角度理解它。
最佳答案
指针变量pt
和pd
存储在堆栈中。他们指向的值,用新分配的,存储在堆上。
如果我写了一个标有“湖”的箭头的标志,这并不意味着标志本身就是一个湖,也不意味着它必须安装在湖中。相反,它应该安装在坚实的地面上,指向湖的方向。
关于c++ - 作者在解释 C++ 中的堆栈和堆时是否犯了错误,或者我误读了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429933/