Pointer arithmetic
Pointer arithmetic in C allows you to perform arithmetic operations on pointers. The arithmetic operations include addition, subtraction, and comparison. Pointer arithmetic is useful when dealing with arrays or when you need to traverse memory blocks.
In C, pointer arithmetic is scaled based on the size of the data type the pointer points to. This means that when you perform arithmetic on a pointer, the address is incremented or decremented by the size of the data type, not by just one byte.
Here are some common pointer arithmetic operations:
Addition and Subtraction:
When you add an integer value n to a pointer, it moves n elements forward, where each element is the size of the data type the pointer points to. Similarly, when you subtract n, it moves n elements backward.
data_type *ptr;
ptr = ptr + n; // Move 'n' elements forward
ptr = ptr - n; // Move 'n' elements backward
For example:
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr; // Points to the first element of the array (arr[0])
// Move the pointer two elements forward
ptr = ptr + 2; // Now points to arr[2], which is 3
Array Access using Pointers:
Pointer arithmetic is commonly used to access elements of an array.
data_type *ptr;
value = ptr[index];
For example:
int arr[] = {10, 20, 30, 40};
int *ptr = arr; // Points to the first element of the array (arr[0])
int first_element = *ptr; // Equivalent to arr[0]
int second_element = *(ptr+1); // Equivalent to arr[1]
int third_element = *(ptr+2); // Equivalent to arr[2]
// and so on...
Comparison of Pointers:
Pointers can be compared using relational operators (<, >, <=, >=, ==, !=). When comparing pointers, you are comparing the memory addresses they point to.
data_type *ptr1, *ptr2;
if (ptr1 < ptr2) {
// ptr1 points to a memory address before ptr2
}
It is essential to ensure that pointer arithmetic is performed within the bounds of the allocated memory to avoid accessing invalid memory locations, which can lead to undefined behavior or segmentation faults. Also, pointer arithmetic is only valid within the bounds of an array or memory block. Trying to access memory outside of what was allocated can lead to undefined behavior as well.