指针变量,var和& var的差异
#include <iostream>
using namespace std;
int main() {
int* z = new int(9);
cout << "address: " << z << endl;
cout << "value: " << *z << endl;
cout << "referance: " << &z << endl;
return 0;
}
看着cout值,我期望地址和参考会提供相同的地址,但是Heres输出是什么:
address: 0x7fc452c032a0
value: 9
referance: 0x7fff5191b8d8
只是对此的原因感到好奇,是普通的值(z),堆在堆中的地址值为9,其中var(&amp; z)是位于堆栈中的指针变量的地址?
这是一个可视化:
是
#include <iostream>
using namespace std;
int main() {
int* z = new int(9);
cout << "address: " << z << endl;
cout << "value: " << *z << endl;
cout << "referance: " << &z << endl;
return 0;
}
Looking at the cout values, I was expecting the address and reference to give the same address, but heres what the output is:
address: 0x7fc452c032a0
value: 9
referance: 0x7fff5191b8d8
Just curious about the reason for this, is the plain value(z) the address of the variable in the heap with a value of 9, where var(&z) is address of the pointer variable which is located in the stack?
Here is a visualization:
Is the
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
&amp; z
指定 Adress 指针int * z
在其中存储分配的adressnew Int(9)
。指针
z
和值9
存储在内存中的两个不同位置。这里没有任何参考的概念,只有 adresses 。
&z
designates the adress of the pointerint * z
where you store the allocated adressnew int(9)
.The pointer
z
and the value9
are stored at two different locations in memory.There is not any notion of reference here, only adresses.
让我首先浏览一些基础知识。
一个变量是一个名称,用于指代内存中的某些位置,该位置具有我们正在使用的值。
使用'&amp;' 获得变量的地址。
指针是存储变量地址的变量。例如,在示例中,您指的是
变量z存储值9 [new Int(9)]的地址。
现在,最终必须将此变量存储在内存中的某个位置,并且可以使用ampersand(&amp;)访问。
这与指针和指针指针(多级指针)的作用相同。
Let me go through some of the basics first.
A variable is a name that is used to refer to some location in the memory, a location that holds a value with which we are working.
Using '&' in C/C++ we can get the address of the variable.
A pointer is a variable that stores the address of a variable. For instance, in the example you are referring to
variable z stores the address of the value 9 [new int(9)].
Now, finally this variable has to be stored at some location in the memory and this can be accessed using ampersand (&).
This is the same way the pointers and pointers to a pointer (multi level pointers) works.
上面的语句意味着
int
类型声明的指针变量。上面的语句意味着一个地址分配给
int
动态类型的指针变量。上面的语句意味着值
9
存储在动态分配中。上面的代码行告诉指针变量的地址
z
。上面的代码行告诉可变
z
中存储的值。上面的代码行告诉动态创建的变量地址。
Above statement implies a pointer variable of
int
type declaration.Above statement implies an address is allocated to pointer variable of
int
type dynamically.Above statement implies value
9
is stored in a dynamically allocated.Above line of code tells the address of pointer variable
z
.Above line of code tells the value stored in the variable
z
.Above line of code tells the dynamically created variable's address.