← Back to C Course | Chapter 7: Pointers | Lesson 3 of 9

C Pointer Arithmetic

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

c
#include <stdio.h>
int main() {
	int arr[3] = {10, 20, 30};
	int *ptr = arr;
	ptr++;
	printf("%d", *ptr);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int arr[3] = {10, 20, 30};
	int *ptr = &arr[2];
	ptr--;
	printf("%d", *ptr);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int arr[3] = {10, 20, 30};
	int *ptr = arr;
	printf("%d", *(ptr + 2));
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int arr[3] = {10, 20, 30};
	int *ptr = &arr[2];
	printf("%d", *(ptr - 1));
	return 0;
}

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

c
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.