[英]Am I understanding pointers correctly? C++
我正在学习C ++中的指针,并且已经阅读了有关它的文章,并且我想我理解了它,尽管我只是想澄清我编写的伪代码。
int someGameHealthAddress = 1693;
int healthIWantItToBe = 20;
int * newHealthValue;
newHealthValue = someGameHealthAddress;
*newHealthValue = healthIWantItToBe;
那上面的权利对吗? 喜欢它的工作方式吗?
编辑:谢谢大家的回答,很高兴我现在记下来了。 您提供了很大的帮助:) EDIT2:我很自豪,现在我已经掌握了这一点。 从外观上看,很多人都难以理解指针。
如果someGameHealthAddress
应该是一个地址,则需要这样声明它。 例如:
int someGameHealth = 1693;
int healthIWantItToBe = 20;
int * someGameHealthAddress; //this is the pointer to an int, which is basically its address
someGameHealthAddress = &someGameHealth; // take address of someGameHealth
*someGameHealthAddress = healthIWantItToBe; // modify the value it points to
在您的代码中此行是错误的:
newHealthValue = someGameHealthAddress;
因为它与变量类型不匹配,所以就像int* = int
。
注意,这是可以从整数类型转换为指针类型的,这几乎总是一个错误,因为您几乎从不知道变量地址在内存中的绝对值。 您通常会找到一些东西,然后使用相对偏移量。 当您进行一些内存黑客攻击时,通常就是这种情况,您的示例似乎就是这种情况。
几乎。 为了获得指向变量的指针,您需要“”的地址&
:
// Set newHealthValue to point to someGameHealth
newHealthValue = &someGameHealth;
(我从变量名中删除了“地址”,因为它不是地址。指针现在包含其地址)。
然后,您的最后一行代码将更改newHealthValue
指向的对象的值,即它将更改someGameHealth
。
这个说法是错误的:
newHealthValue = someGameHealthAddress;
因为左侧具有类型指针,而右侧是整数。 您必须确保类型在分配中匹配。 要获取someGameHealthAddress
的地址,请使用&
:
newHealthValue = &someGameHealthAddress;
现在类型匹配了,因为右侧是整数的地址,因此是指针。
取决于您是否希望指针的值为1693,还是希望指针指向变量someGameHealthAddress的地址
1.将newHealthValue值分配给someGameHealthAddress值
*newHealthValue = someGameHealthAddress;
分配newHealthValue指向someGameHealthAddress变量的地址
* newHealthValue =&someGameHealthAddress;
将newHealthValue的地址分配给someGameHealthAddress变量的值
&newHealthValue = someGameHealthAddress;
将newHealthValue的地址分配给someGameHealthAddress变量的地址
&newHealthValue =&someGameHealthAddress;
*
和&
是c++
使用的两个运算符
& means "the address off"
即&p表示p的地址。
* means "value in the location"
* p表示存储在p中的地址中的值。
为此,p必须是一个指针。(因为p应该保留一个地址)。
这里newHealthValue = someGameHealthAddress;
将给出编译错误。因为someGameHealthAddress是整数,而newHealthValue是整数指针。 int*=int
是类型不匹配
您可以使用以下语句存储someGameHealthAddress的地址
newHealthValue = &someGameHealthAddress
;
which means newHealthValue = (address of)someGameHealthAddress
*newHealthValue = healthIWantItToBe;
在语法上是正确的,因为它存储的值healthIWantItToBe
被指向的地址newHealthValue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.