Pointer arithmetic is a fundamental feature of the C language that makes memory management flexible but also potentially dangerous.
Pointer arithmetic arises from the characteristics of low-level languages and is geared towards working with arrays and processing structured data directly in memory. In C, all pointers "know" the size of the type they point to.
Many developers mistakenly believe that when you add one to a pointer, the address increases by exactly one byte. In reality, the increase occurs by sizeof(type). When working with different data types, especially with structures of varying sizes, it is easy to make mistakes while navigating through memory. Additionally, pointer arithmetic is not allowed with void* — this is a standard mistake.
All arithmetic operations with pointers take into account the size of the corresponding type, which makes operations with arrays as efficient as possible. For example:
#include <stdio.h> int arr[4] = {10, 20, 30, 40}; int *p = arr; printf("%d\n", *(p + 2)); // Prints 30
Here (p + 2) advances the pointer by 2 * sizeof(int) bytes, not just 2 bytes.
Key features:
Is it possible to perform increment/decrement operations on void pointers?
No, the C standard prohibits arithmetic with void*. You must first cast the pointer to a specific type, for example (char*), and then perform the arithmetic.
void *vp = arr; char *cp = (char *)vp; cp++;
What happens if you add a value exceeding the size of the array to a pointer to a structure or an array?
This will result in going out of the valid memory area (undefined behavior). C does not check the boundaries of arrays — the responsibility lies with the programmer.
Is it possible to add two pointers directly together?
No, adding pointers is prohibited and makes no sense. Only the subtraction of two pointers belonging to the same array is permitted.
A young developer, working with an int array via pointers, shifted the pointer by a fixed number of bytes, forgetting the size of the type.
Pros:
Cons:
An experienced developer always uses expressions like (ptr + n), trusting the compiler to scale the shift by the size of the type.
Pros:
Cons: