[英]Convert int to int pointers address
c++ C ++
p
is pointing to specific place p
指向特定位置
int * p
When I try p=p[1]
it says can't convert int to int (using devcpp). 当我尝试
p=p[1]
它说不能将int转换为int(使用devcpp)。
While p=&p[1]
works fine 虽然
p=&p[1]
可以正常工作
Why do I need to do the second method? 为什么需要第二种方法?
p[1]
is an address. p[1]
是一个地址。 So the first method should work? 那么第一种方法应该可行吗? Can you explain me about this error?
您能为我解释这个错误吗?
p[1]
is the same as *(p + 1)
. p[1]
与*(p + 1)
。
You want the address of this element, which is simply (p + 1)
. 您需要此元素的地址 ,即
(p + 1)
。 C++ also allows &p[1]
, as you noticed. 正如您所注意到的,C ++还允许
&p[1]
。
p[1]
is equivalent to *(p + 1)
so it's a value, not an address. p[1]
等效于*(p + 1)
因此它是一个值,而不是地址。 p = p + 1
or just p++
would be what you want. p = p + 1
或只是p++
就是您想要的。
While p
is an int*
, p[1]
is an element from that array, therefore p[1]
is int
. p
是int*
,而p[1]
是该数组中的一个元素,因此p[1]
是int
。
You can do p = &p[1]
in other ways, for instance, p = p + 1
, or p++
. 您可以通过其他方式执行
p = &p[1]
,例如p = p + 1
或p++
。 Both will set p
to the same final value. 两者都将
p
设置为相同的最终值。
Notice when doing such arithmetic operations with pointers, it will not not increment the address by 1, its incrementing it by 1 times the size of one element, so its really the same thing. 请注意,使用指针进行此类算术运算时,它不会将地址增加1,也不会将地址增加一个元素大小的1倍,因此它的确是一样的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.