Webinar: С++ semantics - 06.11
Address arithmetic is a method of calculating an object address using arithmetic operations on pointers, as well as using pointers in comparison operations. Address arithmetic is also known as pointer arithmetic.
According to the C and C++ standards, in pointer arithmetic, the resulting address should remain strictly on the boundary of a single array object (or follow it immediately). Adding or subtracting a pointer shifts it by a multiple of the data type size it points to. For example, there is a pointer to an integer array (4 bytes per element). An increment of the pointer increases its value by 4 (element size). Programmers often do it to get the Nth element in a sequence container.
int array[10] {};
int *ptr = array; // points to the first element
int *next = ptr + 1; // points to the second element
....
int *next = ptr + 9; // points to the last element
Pointer arithmetic cannot be applied to pointers to incomplete types, because their size is unknown. The compiler does not know how many bytes the pointer should be shifted by.
struct SomeType; // Incomplete type
....
SomeType* ptr = ....;
SomeType* next = ptr + 1; // ERROR: 'SomeType *': unknown size
However, there are non-standard compiler extensions that enable you to perform byte arithmetic on untyped pointers (void *).
Pointers and integer variables are not interchangeable objects. The 0 constant is the only exception: it can be assigned to a pointer comparable to a null constant. To show that null is a special value for a pointer, the constant 'NULL' is usually written instead of 0. Since C23 / C++11, it is better to use nullptr for this purpose.
Address arithmetic enables a programmer to work with different types in the same way: by adding and subtracting the required number of elements instead of actually moving bytes. The C language description explicitly specifies the equivalence of the A[i] syntactic structure. It is the i-th element of the A array, and *(A + i) is the content of the element pointed to by the (A + i) expression. It is also assumed that i[A] is equal to A[i]. In other words, all four pointers in the example below point to the same element, just in different ways:
int *a = array + 2;
int *b = 2 + array;
int *c = array[2];
int *d = 2[array];
Address arithmetic is a fundamental concept of C and C++. This is why it's often employed when working with arrays, strings, and dynamically allocated memory. When using address arithmetic, one should be careful. Make sure the calculations are correct to avoid array index out of bounds or access violation.
Due to the complexity of using pointers, many modern high-level programming languages (e.g., Java or C#) do not allow direct memory access using addresses.
Sources
0