C ++中的指针递增 [英] Pointer incrementing in C++
问题描述
这是什么意思:指针增量指向该指针的下一个基本类型的地址?
例如:
p1++; // p1 is a pointer to an int
此语句是否意味着p1
指向的地址应更改为下一个int
的地址,或者仅应将其递增2(假设int
为2个字节),在这种情况下,特定地址可能不包含int
?
我的意思是,如果p1
是0x442012,则p1++
将是0x442014(可能是双精度地址的一部分),还是会指向下一个int
,该地址位于类似0x44201F的地址中? /p>
谢谢
指针算法并不关心指针对象的内容或有效性.它将使用以下公式简单地增加指针地址:
new_value = reinterpret_cast<char*>(p) + sizeof(*p);
(假定指向非const
的指针–否则强制转换将不起作用.)
也就是说,无论指针值和内存对齐如何,它都会使指针增加sizeof(*p)
个字节.
What does this mean: that a pointer increment points to the address of the next base type of the pointer?
For example:
p1++; // p1 is a pointer to an int
Does this statement mean that the address pointed to by p1
should change to the address of the next int
or it should just be incremented by 2 (assuming an int
is 2 bytes), in which case the particular address may not contain an int
?
I mean, if p1
is, say, 0x442012, will p1++
be 0x442014 (which may be part of the address of a double) or will it point to the next int
which is in an address like 0x44201F?
Thanks
Pointer arithmetic doesn’t care about the content – or validity – of the pointee. It will simply increment the pointer address using the following formula:
new_value = reinterpret_cast<char*>(p) + sizeof(*p);
(Assuming a pointer to non-const
– otherwise the cast wouldn’t work.)
That is, it will increment the pointer by an amount of sizeof(*p)
bytes, regardless of things like pointee value and memory alignment.
这篇关于C ++中的指针递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!