Pointer arithmetic means changing the address stored in a pointer by using operations like addition or subtraction. This is useful when working with arrays or other blocks of memory.
Increment (++) and Decrement (–)
When you increment or decrement a pointer, it doesn’t just move by 1 byte. Instead, it moves by the size of the type it points to.
For example, if a pointer points to an integer (which is usually 4 bytes in C), incrementing the pointer will move it by 4 bytes to the next integer.
Example:
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3}; // Array of 3 integers
int *ptr = arr; // Pointer points to arr[0]
printf("%d\n", *ptr); // Output: 1 (points to the first element)
ptr++; // Move the pointer to the next element (arr[1])
printf("%d\n", *ptr); // Output: 2 (now points to the second element)
return 0;
}
Output:
2
Explanation:
- ptr initially points to the first element (arr[0]), which is 1.
- After ptr++, ptr now points to the second element (arr[1]), which is 2.
Adding an Integer to a Pointer
When you add a number to a pointer, the pointer moves by that number of elements, not just bytes. So, adding 3 to a pointer will move it by 3 elements forward, not just 3 bytes.
Example:
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // Pointer points to arr[0]
ptr = ptr + 3; // Move pointer 3 elements forward (arr[3])
printf("%d\n", *ptr); // Output: 4 (now points to arr[3])
return 0;
}
Output:
Explanation:
Initially, ptr points to arr[0] (1).ptr + 3 moves the pointer 3 elements ahead, so it points to arr[3] (4).
Subtracting an Integer from a Pointer
You can subtract an integer from a pointer, and this moves the pointer backward by that number of elements.
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = &arr[3]; // Pointer points to arr[3] (4)
ptr = ptr - 1; // Move pointer 1 element backward (arr[2])
printf("%d\n", *ptr); // Output: 3 (now points to arr[2])
return 0;
}
Output:
Explanation:
- ptr initially points to arr[3] is 4.
- After ptr – 1, it moves 1 elements backward to arr[2] is 3.
Pointer Subtraction (Between Pointers)
You can also subtract one pointer from another. This will tell you how many elements are between the two pointers.
Example:
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr1 = &arr[0]; // Points to arr[0] (1)
int *ptr2 = &arr[4]; // Points to arr[4] (5)
int diff = ptr2 - ptr1; // Difference in elements between ptr2 and ptr1
printf("%d\n", diff);
return 0;
}
Output: