Pointer arithmetic
- C course
- Beginner
- Lesson 75/116
- 5 min
Learn to do arithmetic on pointers with + and -.
Pointer arithmetic
You can add to or subtract from a pointer. ptr + 1 advances by the size of the pointer's type.
int arr[3] = {10, 20, 30};
int *ptr = arr;
printf("%d\n", *(ptr + 1)); /* prints 20 */If an int is 4 bytes, ptr + 1 jumps to the next int; the address goes up by 4. This is the basis of using pointers with arrays.
Walking an array with a pointer
Pointer arithmetic lets you walk an array without using an index. ptr++ moves to the next element each step.
int arr[3] = {10, 20, 30};
int *ptr = arr;
for (int i = 0; i < 3; i++) {
printf("%d\n", *ptr);
ptr++;
}This avoids index math; but the pointer must not go past the array bounds.
Practice Print an array with pointer arithmetic
Define int arr[3] = {10, 20, 30};. Start with int *ptr = arr;. In a for loop, print each element with *(ptr + i) (i = 0, 1, 2). Output should be three lines: 10, 20, 30.
Starter code
#include <stdio.h>
int main(void) {
int arr[3] = {10, 20, 30};
/* bind ptr to arr */
/* in a for loop, print via pointer arithmetic */
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
int arr[3] = {10, 20, 30};
int *ptr = arr;
for (int i = 0; i < 3; i++) {
printf("%d\n", *(ptr + i));
}
return 0;
}Expected output
10 20 30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 For int *ptr, how many bytes does ptr + 1 advance? (int is 4 bytes)
- 1 byte
- 0 bytes
- 8 bytes
- 4 bytes Correct answer
Explanation: If int is 4 bytes, ptr + 1 jumps to the next int; 4 bytes forward.
2 Match pointer arithmetic
| Term | Meaning |
|---|---|
ptr + 1 |
next element |
ptr - 1 |
previous element |
ptr++ |
move forward |
*(ptr + n) |
nth element |
3 Access the second element
int arr[3] = {10, 20, 30};
int *ptr = arr;
printf("%d\n", ____); /* prints 20 */
int arr[3] = {10, 20, 30};
int *ptr = arr;
printf("%d\n", *(ptr + 1)); /* prints 20 */
Explanation: *(ptr + 1) accesses the second element.