C ++ - adding a pointer and element size

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

In the section: Adding a pointer and element size

The following code exists:

// Assume sizeof(int) is 4. int b[100]; // b is an array of 100 ints. int* p; // p is aa 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.

+7
source share
3 answers

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

Pointer arithmetic in C and C ++ is a logical complement, not a numeric addition. Adding one to the pointer means "create a pointer to the object that goes into memory right after that", which means that the compiler automatically scales what you are increasing the pointer to the size of the object that it is pointed at. This prevents you from having a pointer to the middle of the object, or an invalid pointer, or both.

+11
source

The comment in the code you post explains this: adding an integer x to the pointer increases the value of the pointer by x times the sizeof of the type it points to.

This is convenient because it usually does not make sense to change the pointer in smaller increments - you do not want it to point to the middle of one of the elements.

+3
source

since p is a pointer to a type of size 4 bytes. The + operator on pointers is actually a pointer shift. the compiler knows the size of the pointed type and shifts it using the appropriate value

if you change int to short , p will be shifted by 2 bytes

+1
source

All Articles