Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer addition and element size

Tags:

c++

pointers

At: http://www.fredosaurus.com/notes-cpp/arrayptr/26arraysaspointers.html

Under: Pointer addition and element size

There is the following code:

// Assume sizeof(int) is 4.
int b[100];  // b is an array of 100 ints.
int* p;      // p is a a pointer to an int.
p = b;       // Assigns address of first element of b. Ie, &b[0]
p = p + 1;   // Adds 4 to p (4 == 1 * sizeof(int)). Ie, &b[1]

How did "p" in the last line become "4"?

Thanks.

like image 349
Simplicity Avatar asked Jan 23 '11 08:01

Simplicity


People also ask

What happens when you increment a pointer?

When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.

Is Size Of pointer always 8?

The size of any pointer is always 8 on your platform, so it's platform dependent. The sizeof operator doesn't care where the pointer is pointing to, it gives the size of the pointer, in the first case it just gives the size of the array, and that is not the same.

What is the size of a pointer in memory?

Pointers take up the space needed to hold an address, which is 4 bytes on a 32-bit machine and 8 bytes on a 64-bit machine.


1 Answers

(I assume that you mean "1" in the last line, not "p")

Pointer arithmetic in both C and C++ is a logical addition, not a numeric addition. Adding one to a pointer means "produce a pointer to the object that comes in memory right after this one," which means that the compiler automatically scales up whatever you're incrementing the pointer with by the size of the object being pointed at. This prevents you from having a pointer into the middle of an object, or a misaligned pointer, or both.

like image 151
templatetypedef Avatar answered Sep 18 '22 13:09

templatetypedef