Pointer arithmetic refers to performing arithmetic operations like +, -, ++, –, and difference between two pointers, on pointer variables.
Only valid operations:
- Increment (ptr++)
- Decrement (ptr–)
- Addition/Subtraction with integers (ptr + n, ptr – n)
- Pointer difference (ptr1 – ptr2)
Pointer arithmetic depends on the size of the data type the pointer points to. For example, if int is 4 bytes:
int *ptr;
ptr++;- This increases the pointer by 4 bytes, not 1.
Example:
#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("Current value: %d\n", *ptr); // 10
ptr++; // Move to next element
printf("Next value: %d\n", *ptr); // 20
ptr += 2; // Skip two elements
printf("After +2: %d\n", *ptr); // 40
ptr--; // Move one back
printf("After -1: %d\n", *ptr); // 30
return 0;
}Output:
Current value: 10
Next value: 20
After +2: 40
After -1: 30