C++

What is Pointer Arithmetic of C++

The addition and subtraction operators are also applicable to pointers. It is called pointer arithmetic. An integral value can be added to or subtracted from a pointer. The value of the pointer is then changed by the integral value times the size of the type the pointer points at. As the void type is not really a type, but rather the absence of a type, it has no size. Therefore, we cannot perform pointer arithmetic on pointers
to void.

In the code below, let us assume that iNumber is stored at memory location 10,000 and that the integer type has the size of four bytes. Then the pointer pNumber
will assume the values 10,000, 10,004, 10,008, and 10,012, not the values 10,000, 10,002, 10,003, and 10,013, as pointer arithmetic always take the size of the type
into consideration.



int iNumber = 100;
int* pNumber = &iNumber;
pNumber = pNumber + 1;
*pNumber = iNumber + 1;
pNumber = pNumber + 1;
*pNumber = iNumber + 2;
pNumber = pNumber + 1;
*pNumber = iNumber + 3;

It is also possible to subtract two pointers pointing at the same type. The result will be the difference in bytes between their two memory locations divided by the size of the type.

int array[] = {1, 2, 3};
int* p1 = &array[0];
int* p2 = &array[2];
int iDiff = p2 - p1; // 2

The index notation for arrays is equivalent to the dereferring of pointers together with pointer arithmetic. The second and third lines of the following code are by definition interchangeable.

int array[] = {1, 2, 3};
array[1] = array[2] + 1;
*(array + 1) = *(array + 2) + 1;

6月 16, 2011

You Might Also Like

0 comments