Topic 29 of 91 5. C++ Pointers and References Interactive Tutorial

Pointers With Arrays in C++: Traversing Elements Through Addresses

15 mins read Last updated: 26 Sep 2026 21,800 views

Direct Answer & Core Concept

Pointers and arrays are closely connected in C++. A pointer can store the address of an array element and use that address to access or traverse elements in the array.

Instead of accessing array elements only through indexes, you can use pointers to move between elements and work directly with their memory addresses.

This concept is useful when working with arrays, functions, dynamic memory, strings, and data structures.

Detailed Explanation & Mechanics

1. What Are Pointers With Arrays in C++?

An array stores multiple elements of the same data type in a sequence of memory locations.

A pointer can store the address of an array element. In many expressions, an array name automatically converts into a pointer to its first element.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int* ptr = numbers;

    cout << "First element: " << *ptr << endl;

    return 0;
}

Output:

Explanation

  • numbers is an integer array.

  • ptr is an integer pointer.

  • numbers converts to the address of its first element in this assignment.

  • *ptr accesses the first array element.

The following two statements are equivalent:

Both initialize ptr with the address of the first element.

2. Understanding Array Memory Addresses

Array elements are stored in contiguous memory locations.

This means the elements are arranged one after another, with no gaps between consecutive elements of the array.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40};

    for (int i = 0; i < 4; i++) {
        cout << "Value: " << numbers[i]
             << " Address: " << &numbers[i] << endl;
    }

    return 0;
}

Example output:

main.cpp
Run Online
Value: 10 Address: 0x1000
Value: 20 Address: 0x1004
Value: 30 Address: 0x1008
Value: 40 Address: 0x100c

The addresses are illustrative. Actual addresses depend on the system and program execution.

If an integer occupies 4 bytes on the system, consecutive elements will typically have addresses separated by 4 bytes.

The important point is that array elements are stored in contiguous memory.

3. Accessing Array Elements Using Pointers

You can use a pointer to access array elements without directly writing an array index.

Syntax

Here:

  • pointer stores the address of the first array element.

  • index represents the number of elements to move forward.

  • * accesses the value at the resulting address.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int* ptr = numbers;

    cout << *(ptr + 0) << endl;
    cout << *(ptr + 1) << endl;
    cout << *(ptr + 2) << endl;
    cout << *(ptr + 3) << endl;
    cout << *(ptr + 4) << endl;

    return 0;
}

Output:

Explanation

ExpressionArray elementValue
*(ptr + 0)numbers[0]10
*(ptr + 1)numbers[1]20
*(ptr + 2)numbers[2]30
*(ptr + 3)numbers[3]40
*(ptr + 4)numbers[4]50

This is called pointer-based array access.

4. Traversing an Array Using Pointer Arithmetic

Pointer arithmetic allows you to move between array elements by incrementing or decrementing a pointer.

When you increment a pointer, it moves to the next element of its pointed-to type.

Example: Using the increment operator

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int* ptr = numbers;

    for (int i = 0; i < 5; i++) {
        cout << *ptr << endl;
        ptr++;
    }

    return 0;
}

Output:

How does it work?

  1. The pointer initially points to the first element.

  2. *ptr reads the current element.

  3. ptr++ moves the pointer to the next element.

  4. The loop repeats until all five elements have been processed.

Important pointer arithmetic operations

OperationDescription
ptr++Moves to the next element
ptr--Moves to the previous element
ptr + 2Points two elements forward
ptr - 2Points two elements backward
*ptrAccesses the current element
ptr[i]Accesses the element at offset i

Pointer arithmetic must stay within the same array object or its one-past position. The one-past pointer must never be dereferenced.

5. Difference Between Array Indexing and Pointer Access

C++ allows you to access array elements using either array indexing or pointer expressions.

Both approaches can access the same element.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {5, 10, 15, 20};

    int* ptr = numbers;

    cout << numbers[2] << endl;
    cout << *(ptr + 2) << endl;
    cout << ptr[2] << endl;

    return 0;
}

Output:

Comparison

Array indexingPointer access
numbers[0]*(ptr + 0)
numbers[1]*(ptr + 1)
numbers[2]*(ptr + 2)
numbers[3]*(ptr + 3)

The expression ptr[i] is also equivalent to *(ptr + i).

Remember: Array indexing is often easier to read. Pointer access is useful when learning memory operations and when working with pointer-based interfaces.

6. Printing All Array Elements Using a Pointer

You can traverse an array using a pointer and a loop without directly using array indexing.

Example: Using a while loop

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {12, 24, 36, 48, 60};

    int* ptr = numbers;
    int* end = numbers + 5;

    while (ptr < end) {
        cout << *ptr << endl;
        ptr++;
    }

    return 0;
}

Output:

Explanation

  • ptr points to the first element.

  • end points one position past the final element.

  • The loop continues while ptr is before end.

  • *ptr prints the current element.

  • ptr++ advances to the next element.

Using a one-past pointer as the loop boundary is a common C++ traversal technique. Do not dereference end.

7. Modifying Array Elements Using Pointers

Pointers can also modify array elements.

When you assign a new value through a pointer, the corresponding array element changes.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int* ptr = numbers;

    *(ptr + 0) = 100;
    *(ptr + 1) = 200;
    *(ptr + 2) = 300;

    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << endl;
    }

    return 0;
}

Output:

Explanation

  • *(ptr + 0) = 100 updates the first element.

  • *(ptr + 1) = 200 updates the second element.

  • *(ptr + 2) = 300 updates the third element.

The pointer provides access to the original array elements, so the changes are visible through the array name.

8. Passing an Array to a Function Using a Pointer

When an array is passed to a function as a parameter, the parameter is adjusted to a pointer type.

The function can use that pointer to access the original array elements.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

void display(int* ptr, int size) {
    for (int i = 0; i < size; i++) {
        cout << *(ptr + i) << endl;
    }
}

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    display(numbers, 5);

    return 0;
}

Output:

Explanation

  • display() receives an integer pointer and an array size.

  • numbers converts to a pointer to its first element when passed.

  • The function accesses each element using pointer arithmetic.

  • The size parameter tells the function how many elements it can safely process.

Important: An array parameter does not automatically carry the array's length. Pass the size separately, or use a suitable standard library container or array reference when preserving size information is important.

9. Finding the Sum of Array Elements Using Pointers

Pointers can be used to process array elements and calculate their total.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int* ptr = numbers;
    int sum = 0;

    for (int i = 0; i < 5; i++) {
        sum += *(ptr + i);
    }

    cout << "Sum: " << sum << endl;

    return 0;
}

Output:

Explanation

The loop accesses each element through the pointer and adds it to sum.

This approach can be used for calculating totals, averages, minimum values, and maximum values.

10. Finding the Largest Element Using Pointers

You can compare array elements through a pointer to find the largest value.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {25, 80, 15, 100, 45};

    int* ptr = numbers;
    int largest = *ptr;

    for (int i = 1; i < 5; i++) {
        if (*(ptr + i) > largest) {
            largest = *(ptr + i);
        }
    }

    cout << "Largest value: " << largest << endl;

    return 0;
}

Output:

The program starts with the first element as the largest value. It compares the remaining elements and updates the result whenever it finds a larger number.

11. Reversing an Array Using Pointers

Pointers can also traverse an array from both ends.

One pointer starts at the first element, and another starts at the last element. Their values are swapped until the pointers meet or cross.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int* left = numbers;
    int* right = numbers + 4;

    while (left < right) {
        int temp = *left;
        *left = *right;
        *right = temp;

        left++;
        right--;
    }

    for (int value : numbers) {
        cout << value << " ";
    }

    return 0;
}

Output:

This technique is useful for understanding two-pointer algorithms.

For arrays of different sizes, calculate the final element using the array's actual size rather than hard-coding the index.

12. Pointers With Two-Dimensional Arrays

C++ also supports pointers with multidimensional arrays.

A two-dimensional array is stored as an array of rows, with each row containing its own sequence of elements.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[2][3] = {
        {10, 20, 30},
        {40, 50, 60}
    };

    int (*ptr)[3] = numbers;

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            cout << ptr[i][j] << " ";
        }

        cout << endl;
    }

    return 0;
}

Output:

Explanation

  • numbers is a two-dimensional array with two rows and three columns.

  • int (*ptr)[3] declares a pointer to an array of three integers.

  • ptr[i][j] accesses the element in row i and column j.

The parentheses are important. int (*ptr)[3] is a pointer to an array, while int* ptr[3] declares an array of three integer pointers.

13. Pointer to an Array vs Array of Pointers

These two declarations may look similar, but they have different meanings.

Pointer to an array

main.cpp
Run Online
int numbers[3] = {10, 20, 30};

int (*ptr)[3] = &numbers;

Here, ptr points to the entire array of three integers.

Array of pointers

main.cpp
Run Online
int first = 10;
int second = 20;
int third = 30;

int* ptr[3] = {&first, &second, &third};

Here, ptr is an array containing three integer pointers.

Comparison

FeaturePointer to an arrayArray of pointers
Declarationint (*ptr)[3]int* ptr[3]
MeaningPoints to an entire arrayStores multiple pointers
Common useMultidimensional arraysReferencing separate variables or objects
StructureOne pointerArray of pointer elements

14. Difference Between Array Names and Pointers

An array name often converts to a pointer to its first element, but an array and a pointer are not the same thing.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30};

    int* ptr = numbers;

    cout << "Array first element: " << *numbers << endl;
    cout << "Pointer first element: " << *ptr << endl;

    cout << "Array size: " << sizeof(numbers) << endl;
    cout << "Pointer size: " << sizeof(ptr) << endl;

    return 0;
}

Example output on a system with 4-byte integers and 8-byte pointers:

main.cpp
Run Online
Array first element: 10
Pointer first element: 10
Array size: 12
Pointer size: 8

The sizes shown are system-dependent.

Important differences

ArrayPointer
Stores its elementsStores an address
Has a fixed number of elementsCan point to different objects of a compatible type
sizeof(array) gives total array storage sizesizeof(pointer) gives pointer size
Cannot be reassigned as a wholeCan be reassigned
Array name converts to a pointer in many expressionsPointer is already an address-holding variable

15. Common Mistakes When Using Pointers With Arrays

Beginners often make these mistakes when working with pointers and arrays.

1. Accessing elements outside the array

main.cpp
Run Online
int numbers[3] = {10, 20, 30};

int* ptr = numbers;

// Invalid: ptr[3] is outside the array.

Solution: Access only valid indexes, from 0 to size - 1.

2. Dereferencing an uninitialized pointer

main.cpp
Run Online
int* ptr;

// Unsafe: the pointer is uninitialized.

Solution: Initialize the pointer with a valid address or nullptr.

3. Forgetting pointer increment

If you print *ptr repeatedly without moving the pointer or changing the index, you will keep reading the same element.

Solution: Use ptr++ or *(ptr + i) when traversing the array.

4. Confusing a pointer with an array

An array name and a pointer are related, but they are different types.

Solution: Understand array-to-pointer conversion and the difference between sizeof(array) and sizeof(pointer).

5. Using an invalid pointer after the array's lifetime ends

A pointer becomes invalid when the object it refers to no longer exists.

Solution: Make sure the array remains alive whenever you access it through a pointer.

6. Incorrect pointer declaration

Only first is a pointer. second is an integer.

Solution: Declare each pointer clearly:

16. Best Practices for Pointers With Arrays

Follow these practices when using pointers with arrays:

  1. Initialize pointers before accessing array elements.

  2. Always know the array's size.

  3. Avoid accessing elements outside the array boundaries.

  4. Use const int* when a function should not modify array elements.

  5. Prefer array indexing when it makes the code easier to understand.

  6. Use pointer arithmetic when it makes the intended operation clearer.

  7. Avoid returning pointers to local arrays.

  8. Use standard library containers such as std::array and std::vector when appropriate.

  9. Keep pointer and array lifetimes clear.

  10. Compile and test examples with warnings enabled.

17. Frequently Asked Questions (FAQs)

Q1. How are pointers related to arrays in C++?

In many expressions, an array name converts to a pointer to its first element. A pointer can then be used to access and traverse the array elements.

Q2. How do you declare a pointer for an array?

For an integer array, you can declare and initialize a pointer like this:

main.cpp
Run Online
int numbers[] = {10, 20, 30};
int* ptr = numbers;

Q3. What does *(ptr + i) mean?

It accesses the array element located i positions after the element pointed to by ptr.

Q4. Can we traverse an array using a pointer?

Yes. You can use pointer increment (ptr++) or pointer arithmetic (*(ptr + i)) to access array elements one by one.

Q5. Can pointers modify array elements?

Yes. If the pointer points to a modifiable array element, you can change its value using an expression such as *ptr = 100.

Q6. What is the difference between numbers[i] and *(numbers + i)?

Both expressions access the same array element. C++ defines array subscripting in terms of pointer arithmetic and dereferencing.

Q7. Can we use pointers with two-dimensional arrays?

Yes. A pointer to an array can be used to access rows and columns of a two-dimensional array.

Q8. What is an array of pointers?

An array of pointers is an array whose elements are pointers. For example, int* ptr[3] declares an array containing three integer pointers.

Q9. Are arrays and pointers identical in C++?

No. Arrays and pointers are different types. Array-to-pointer conversion makes them behave similarly in many expressions, but they have different storage and size properties.

Q10. Why are pointers useful for array traversal?

Pointers allow direct access to array elements through their addresses. They are useful for understanding memory, working with low-level interfaces, and implementing pointer-based algorithms.

Runnable Code Example: Pointers With Arrays in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>

int main() {
    int buffer[5] = {10, 20, 30, 40, 50};
    int* ptr = buffer; // Decays to &buffer[0]

    std::cout << "Traversing via Pointer Arithmetic:
";
    for (int i = 0; i < 5; ++i) {
        std::cout << "Element [" << i << "]: " << *(ptr + i) 
                  << " at address: " << (ptr + i) << "
";
    }

    // Pointer difference (number of elements between pointers)
    int* endPtr = buffer + 5;
    std::cout << "Total elements (end - start): " << (endPtr - ptr) << "
";
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: What happens when you subtract two pointers in C++?

A: Pointer subtraction (`ptr2 - ptr1`) returns a signed integer of type `std::ptrdiff_t` representing the number of array elements between the two memory addresses, not the raw byte difference.
Q

Q: Why is pointer decay a potential source of bugs?

A: When an array is passed to a function, it decays to a pointer, losing its compile-time size information (i.e. `sizeof(arr)` returns pointer size 8 bytes rather than total array bytes).

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Use std::array or std::vector instead of C-style raw arrays to preserve size information.
2. Use std::span (C++20) for non-owning views over contiguous memory buffers.
3. Never increment pointers beyond the past-the-end element (arr + N).