开发者

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


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.


p1++ gives rise to assembly language instructions which increment p1 by the size of what it points to. So you get

(char *)p1 = (char *)p1 + sizeof (object pointed to by p1)

(When this question was answered) Typically an int is 4 bytes, so it would increment by 4, but it depends on the sizeof() on your machine.

It does not go to "the next int".

An example: assume a 4 byte address and p1 = 0x20424 (where p1 is an int*). Then

p1++

would set the new value of p1 to 0x20428. NOT 0x20425.


If p1 is pointing into the element of index n of an array of objects of type int (a non-array object counts as an array of length 1 for this purpose), then after p1++, p1 is either:

  • Pointing to the element of index n+1 if the array is of length greater than n+1.
  • The 'past-the-end' address of the array, if the array is of length exactly n+1.

p1++ causes undefined behavior if p1 is not pointing to an element of an array of objects of type int.

The only meaning that the C and C++ languages give to the notion of "address" is the value of a pointer object.

Any relationship that C/C++'s notion of address has to the notion of a numeric addresses you'd consider in assembly language is purely an implementation detail (albeit, an extremely common implementation detail).


Pointer arithmetic are done in sizoeof(*pointer) multiples - that is, for a pointer to int, increment will advance to the next integer (or 4 bytes for 32 bit integers).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜