How to Increment and Decrement Pointer in C: Simple Guide
In C, you can increment a pointer using
ptr++ to move it to the next memory location of its type, and decrement it using ptr-- to move it to the previous location. These operations adjust the pointer by the size of the data type it points to.Syntax
To move a pointer forward or backward in memory, use the increment (++) or decrement (--) operators. This changes the pointer's address by the size of the data type it points to.
ptr++: Moves pointer to the next element.ptr--: Moves pointer to the previous element.
c
ptr++; ptr--;
Example
This example shows how a pointer to an integer array is incremented and decremented to access different elements.
c
#include <stdio.h> int main() { int arr[] = {10, 20, 30, 40}; int *ptr = arr; // Pointer to first element printf("Current value: %d\n", *ptr); // 10 ptr++; // Move to next element printf("After increment: %d\n", *ptr); // 20 ptr++; // Move to next element printf("After another increment: %d\n", *ptr); // 30 ptr--; // Move back to previous element printf("After decrement: %d\n", *ptr); // 20 return 0; }
Output
Current value: 10
After increment: 20
After another increment: 30
After decrement: 20
Common Pitfalls
Common mistakes when incrementing or decrementing pointers include:
- Incrementing beyond the array bounds, which causes undefined behavior.
- Incrementing a
void*pointer directly, which is not allowed because its size is unknown. - Confusing pointer arithmetic with integer arithmetic; pointer increments move by the size of the pointed type, not by 1 byte.
c
#include <stdio.h> int main() { int arr[3] = {1, 2, 3}; int *ptr = arr; // Wrong: Incrementing beyond array size ptr = arr + 3; // Points just past the last element // Dereferencing ptr here is unsafe and causes undefined behavior // Correct: Stay within bounds ptr = arr + 2; // Points to last element printf("Last element: %d\n", *ptr); return 0; }
Output
Last element: 3
Key Takeaways
Use
ptr++ to move a pointer to the next element and ptr-- to move to the previous element.Pointer arithmetic moves by the size of the data type, not by one byte.
Avoid incrementing pointers beyond the array bounds to prevent undefined behavior.
You cannot increment
void* pointers directly because their size is unknown.Always ensure pointers point to valid memory before dereferencing after increment or decrement.