Pointer arithmetic lets you move through memory locations easily by adding or subtracting numbers to pointers.
0
0
Pointer arithmetic
Introduction
When you want to access elements in an array using pointers.
When you need to loop through a block of memory efficiently.
When working with strings as arrays of characters.
When manipulating data structures like linked lists using pointers.
When you want to calculate the distance between two memory addresses.
Syntax
C
pointer + n // moves pointer forward by n elements pointer - n // moves pointer backward by n elements pointer++ // moves pointer to next element pointer-- // moves pointer to previous element pointer1 - pointer2 // gives number of elements between two pointers
Pointer arithmetic moves in units of the size of the data type the pointer points to.
Adding 1 to a pointer moves it to the next element, not just the next byte.
Examples
Moves pointer p two integers ahead in the array.
C
int *p = arr; p = p + 2;
Moves pointer c to the next character in the string.
C
char *c = str;
c++;Calculates how many elements are between pointers p1 and p2.
C
int diff = p2 - p1;Sample Program
This program shows how to move a pointer through an integer array and access different elements using pointer arithmetic.
C
#include <stdio.h> int main() { int arr[] = {10, 20, 30, 40, 50}; int *p = arr; // points to first element printf("First element: %d\n", *p); p = p + 3; // move pointer 3 elements ahead printf("Fourth element: %d\n", *p); p--; printf("Third element after moving back: %d\n", *p); int diff = p - arr; printf("Pointer is %d elements away from start\n", diff); return 0; }
OutputSuccess
Important Notes
Pointer arithmetic only works correctly with pointers pointing inside the same array or one past the end.
Be careful not to move pointers outside valid memory, or your program may crash.
Summary
Pointer arithmetic lets you move pointers by elements, not bytes.
You can add, subtract, increment, and decrement pointers.
Subtracting two pointers gives the number of elements between them.