CPP中分配的内存和现有地址有什么区别?

What is difference between allocated memory and existing address in CPP?

int *n=new int;
*n=20;
cout<<n<<endl<<*n<<endl<<&n;

当编译上面的代码时,我得到的输出是

0xa41510 20 0x6ffe08

现在 'n''&n' 有什么区别。如果新内存分配给 'n' 那么为什么它的地址不同?

对不起,如果这有点愚蠢。

     n
----------- 
| 0xa41510 |
------------
address : 0x6ffe08

--------
|  20  |
--------
 address : 0xa41510

写的时候

int *n=new int

you are telling that you need a memory to store an integer type so new returns the address of memory location allocated which is then stored in n

声明后

*n=20

您在 n

中存储的地址存储了 20

NOTE : '*' is the indirection or dereferencing operator when applied to a pointer, it accesses the object the pointer points to.

所以现在当我们打印输出时

std::cout<<n; 

prints 0xa41510 

As this is the value stored in n which is the address of memory location where 20 is stored

std::cout<<*n ;

prints 20 

> As it prints the value at the address stored in n

std::cout<<&n;  

prints 0x6ffe08 

> As it the address of n

注意

& produces the address of the variable

你可以认为'int*'是一个新的类型,比如typedef int * INT_POINTER。 如果理解了int和int*的关系,那么理解INT_POINTER和INT_POINTER*的关系就没有问题了。一样的。

ex :) 下面两行意思相同

int a = 0; int * b = &a;
INT_POINTER c = new int; INT_POINTER* d = &c;