如何解决*pt = x;不工作C++ 中 * 和 & 的含义
我完全是新手,很难消化 C++ 中的指针部分。
我的理解是这样的:
要访问地址的内容,请使用 *
要访问内容的地址,请使用 &
所以基本上我的问题是:为什么下面的代码会抛出错误?
int x = 10;
int *pt;
*pt = x;
为什么我应该以如下格式编码?
int x = 10;
int *pt;
pt = &x;
我也看不懂 *pt = &x;
行。 *pt
应该是内容,而不是地址。为什么可以?
int x = 10;
int *pt = &x;
同样,为了让temp
与n1
共享同一个地址,我认为应该是
int n1 = 1;
int &temp = &n1;
但教科书说正确的代码在下面。
int n1 = 1;
int &temp = n1;
需要帮助!
解决方法
您将表达式中 *
和 &
的含义与其在变量类型声明中的含义混淆了。在变量类型中,*
只是表示这个变量是一个指针,而 &
表示它是一个引用,例如:
int *pt = &x;
实际上的意思是“声明一个指向 int
的指针,名称为 pt
并将 x
的地址分配给它”。虽然
int &temp = n1;
的意思是“声明一个名为 int
的对 temp
的引用并将 n1
分配给它,这样 temp
指代与 n1
相同的内存”。
指针是“对特定类型内存的引用”。在示例中,您写了 int *pt;
而是尝试像这样考虑:
int x = 10;
// Declare a pointer to location in memory.
// That memory is holding (or will be) value of type int.
int* pt;
// What would be be the meaning of this? *pt doesn't really mean anything.
// int* means that it is points to type of integer
*pt = x;
类似的方法适用于 &x
,它只是用于:
- “我知道有
x
类型的变量int
,我想获取地址(该 int 的第一个字节)”。
// Again from the example,you declare int x to value 10.
int x = 10;
// Declare pointer for int type.
int* pt;
// Set pointer (variable that specifies the location in memory)
// to address of variable x (so you point "pointer pt" to location in memory
// where variable x sits
pt = &x;
最后,如果你把这些点联系起来:
int x = 10;
// 1st declare pointer of type int
// point the pointer to the value x
int* pt = &x;
,
为什么下面的代码会抛出错误?
1> int x = 10;
2> int *pt;
3> *pt = x;
第3行的*pt
访问了int
指向的pt
,但是此时pt
的值是未定义的。
为什么我应该以如下格式编码?
int x = 10;
int *pt;
pt = &x;
将指向x
的指针分配给pt
,所以现在指针pt
指向x
。
我也看不懂 *pt = &x;线。 *pt 应该是内容,而不是 地址。为什么可以?
int x = 10;
int *pt = &x;
不,pt
是一个变量,而 int *
是它的类型。这段代码和上一段意思一样。
同样,为了让 temp 与 n1 共享相同的地址,我认为它 应该
int n1 = 1;
int &temp = &n1;
但教科书说正确的代码在下面。
int n1 = 1;
int &temp = n1;
int &
是 C++ 引用类型,它不是指针,因此不需要 &
运算符来获取 n1
的地址。此时 pt
已经绑定到 n1
。
我认为您对“&”和“*”的含义感到困惑。
简而言之,
&x:一碗x地址。 *pt:选择地址的叉子(仅地址)。
如果你声明为'int *pt',你就不需要声明为'*pt=&x'。因为'pt'已经是指针变量了。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。