Pointer Arithmetic
- Siddharth Sharma
- Nov 7, 2024
- 2 min read
Pointer arithmetic refers to operations that involve pointers in C and C++. These operations allow pointers to move through memory locations, particularly useful when dealing with arrays or dynamically allocated memory.
Basics of Pointer Arithmetic
Pointer arithmetic operations include:
Increment (++) and decrement (--).
Addition (+) and subtraction (-) with integers.
When you perform arithmetic on pointers, the pointer moves by the size of the data type it points to, not by a single byte. For example, incrementing an int* pointer (which typically points to a 4-byte integer) moves it forward by 4 bytes, to point to the next integer in memory.
Example of Pointer Arithmetic
Consider an array and a pointer to its first element:
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int* ptr = arr; // Points to the first element of arr
printf("Initial value pointed by ptr: %d\n", *ptr); // Outputs 10
// Increment pointer
ptr++; // Moves ptr to the next integer in the array
printf("After increment, value pointed by ptr: %d\n", *ptr); // Outputs 20
// Add an integer to pointer
ptr = ptr + 2; // Moves ptr forward by 2 more integers
printf("After adding 2, value pointed by ptr: %d\n", *ptr); // Outputs 40
// Decrement pointer
ptr--; // Moves ptr back by one integer
printf("After decrement, value pointed by ptr: %d\n", *ptr); // Outputs 30
return 0;
}Explanation:
ptr++: Moves ptr to the next integer in the array. Since int typically occupies 4 bytes, ptr increments by 4 bytes.
ptr + 2: Moves ptr forward by 2 integers (or 8 bytes).
ptr--: Moves ptr backward by one integer.
Output:
Initial value pointed by ptr: 10
After increment, value pointed by ptr: 20
After adding 2, value pointed by ptr: 40
After decrement, value pointed by ptr: 30Valid Pointer Arithmetic Operations
Pointer arithmetic is allowed with:
Array traversal: Easily move from one element to the next in an array.
Dynamic memory traversal: Navigate through dynamically allocated memory.
For instance, with int arr[5], arr[i] is equivalent to *(arr + i).
Rules and Restrictions
Same Type Addition/Subtraction: You can add or subtract an integer from a pointer, but adding two pointers is not allowed.
Difference of Pointers: You can subtract two pointers to find the number of elements between them, but they must point to elements within the same array.
int diff = &arr[4] - &arr[0]; // The difference in elements
printf("Difference in elements: %d\n", diff); // Outputs 4Summary
Pointer arithmetic is powerful in C and C++ and allows:
Traversing arrays and contiguous memory.
Moving pointers relative to the size of the data they point to.
It requires caution, as incorrect pointer arithmetic can lead to undefined behavior if it accesses memory outside the intended range.




Comments