CodeBlanks Logo Icon CodeBlanks

Pointer arithmetic

Learn to do arithmetic on pointers with + and -.

Pointer arithmetic

Pointers support arithmetic with + and -. Adding +1 to a pointer moves it to the next element; it steps by the size of the type. For example, on an int* p, p + 1 moves p by one int size.

This is useful for walking arrays. An array's name is the address of its first element; you can start with int* p = arr; and reach elements with *(p + 1), *(p + 2). This is the same as writing arr[1].

Array and pointer connection

An array's name is interpreted as the address of its first element. arr and &arr[0] mean the same. So you can write int* p = arr;; p now points to the start of the array.

arr[i] is actually a shortcut for *(arr + i). So indexing is a combination of pointer arithmetic and dereference. This connection reflects the low-level nature of C++; but in everyday code, writing arr[i] is more readable.

Practice Walk an array with a pointer

Declare int arr[] = {10, 20, 30};. Bind p to the start of the array with int* p = arr;. Print the second element using *(p + 1) with std::cout.

Starter code

main.cpp
#include <iostream>

int main() {
    // Declare the array
    // Bind p to the array
    // Print the second element
    return 0;
}

Sample solution

main.cpp
#include <iostream>

int main() {
    int arr[] = {10, 20, 30};
    int* p = arr;
    std::cout << *(p + 1) << "\n";
    return 0;
}

Expected output

20

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does this code print?

main.cpp
int arr[] = {10, 20, 30};
int* p = arr;
std::cout << *(p + 1);
  • 10
  • 20 Correct answer
  • 0
  • 30

Explanation: *(p + 1) gives the second element of the array, which is 20.

2 Match each expression to its meaning

Term Meaning
p + 1 Next element
*(p + 1) Second value
arr Array name
int* p = arr Binding

3 Pointer arithmetic

Question
std::cout << *(p ____ 1);
Answer
std::cout << *(p + 1);

Explanation: *(p + 1) accesses the element after p.

All lessons in Beginner