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.
The compiler will add sizeof(int)
(usually 4) to the numeric value of the pointer. If p1 is 0x442012 before the increment, then after the increment it will be 0x442012 + 4 = 0x442016.
Mind you, 0x442012 is not a multiple of 4, so it is unlikely to be the address of a valid four-byte int, though it would be fine for your two-byte ints.
It certainly won't go looking for the next integer. That would require magic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With