Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer incrementing in C++

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

like image 308
afaolek Avatar asked Jun 27 '11 11:06

afaolek


2 Answers

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.

like image 198
Konrad Rudolph Avatar answered Oct 06 '22 02:10

Konrad Rudolph


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.

like image 37
Marcelo Cantos Avatar answered Oct 06 '22 02:10

Marcelo Cantos