*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;

同样,要使tempn1共享相同的地址,我认为应该是

int n1 = 1;
int &temp = &n1;

但教科书说正确的代码在下面。

int n1 = 1;
int &temp = n1;

需要帮助!

您将表达式中*&的含义与它们在变量类型声明中的含义混淆了。在变量类型中,*只意味着这个变量是一个指针,而&意味着它是一个引用,例如:

int *pt = &x;

实际上意味着"声明一个指向int的指针,名称为pt并为其分配x地址"。而

int &temp = n1;

意思是"声明对名为tempint的引用并为其分配n1,以便temp引用与n1相同的内存"。

我认为您对"&"和"*"的含义感到困惑。

简而言之

&x:一碗 x 地址。 *pt:选择地址(仅限地址)的分叉。

如果你声明为'int *pt',你不需要声明为'*pt=&x'。因为"pt"已经是指针变量了。

指针是"对特定类型的内存的引用"。在示例中,您写了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,这只是以下方面的快捷方式:

  • "我知道有int类型的可变x,我想得到地址(该整数的第一个字节)"。
// 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;

为什么下面的代码会抛出错误?

3 行中的

1> int x = 10;
2> int *pt;
3> *pt = x;
*pt访问pt指向的int,但此时pt的值尚未定义。

为什么我应该使用以下格式编码?

int x = 10;
int *pt;
pt = &x;

指向x的指针分配给pt,因此现在指针pt指向x

我也无法理解 *pt = &x; 行。 *pt 应该是内容,而不是 地址。为什么没问题?

int x = 10;
int *pt = &x;

不,pt是一个变量,int *是它的类型。此代码与前一个代码的含义相同。

同样,为了使临时与n1共享相同的地址,我认为它 应该是

int n1 = 1;
int &temp = &n1;

但教科书说正确的代码在下面。

int n1 = 1;
int &temp = n1;

int &是C++引用类型,但它不是指针,因此不需要&运算符来获取n1的地址。此时pt已经绑定到n1

最新更新