C Pointer Arithmetic
In this page:
Incrementing a Pointer
For example, if ptr points to an int (4 bytes on most systems) at address 1000, then ptr++ makes it point to address 1004, not 1001 -- the compiler automatically scales the increment by sizeof(the pointed-to type).
Example: Incrementing a Pointer
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
int *ptr = arr;
ptr++;
printf("%d", *ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Decrementing a Pointer
Just as with incrementing, ptr-- moves the pointer back by exactly one element's worth of bytes, which is why pointer arithmetic only makes sense within (or one past the end of) a single array -- there's no guarantee about what lies before or after it in memory.
Example: Decrementing a Pointer
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
int *ptr = &arr[2];
ptr--;
printf("%d", *ptr);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Adding Integers to Pointers
ptr + n is equivalent to walking n elements forward from ptr's current position, and is the mechanism underlying the equivalence between arr[i] and *(arr + i) -- both compute the same address before dereferencing it.
Example: Adding Integers to Pointers
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
int *ptr = arr;
printf("%d", *(ptr + 2));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Subtracting Integers from Pointers
This works the same way as addition but in reverse, and is commonly used when iterating an array backward from a pointer that started at the last element, decrementing toward the first.
Example: Subtracting Integers from Pointers
#include <stdio.h>
int main() {
int arr[3] = {10, 20, 30};
int *ptr = &arr[2];
printf("%d", *(ptr - 1));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Pointer Subtraction
This is genuinely useful for computing distances -- for example, if you have a pointer to the start and end of a substring within a larger array, subtracting them tells you exactly how many characters lie between them.
Example: Pointer Subtraction
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *start = &arr[0];
int *end = &arr[4];
printf("%ld", end - start);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: