#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int* ptr = numbers;
cout << "First element: " << *ptr << endl;
return 0;
}Pointers With Arrays in C++: Traversing Elements Through Addresses
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
Output:
First element: 10Explanation
numbersis an integer array.ptris an integer pointer.numbersconverts to the address of its first element in this assignment.*ptraccesses the first array element.
The following two statements are equivalent:
int* ptr = numbers;int* ptr = &numbers[0];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
#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:
Value: 10 Address: 0x1000
Value: 20 Address: 0x1004
Value: 30 Address: 0x1008
Value: 40 Address: 0x100cThe 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
*(pointer + index)Here:
pointerstores the address of the first array element.indexrepresents the number of elements to move forward.*accesses the value at the resulting address.
Example
#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:
10
20
30
40
50Explanation
| Expression | Array element | Value |
|---|---|---|
*(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
#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:
10
20
30
40
50How does it work?
The pointer initially points to the first element.
*ptrreads the current element.ptr++moves the pointer to the next element.The loop repeats until all five elements have been processed.
Important pointer arithmetic operations
| Operation | Description |
|---|---|
ptr++ | Moves to the next element |
ptr-- | Moves to the previous element |
ptr + 2 | Points two elements forward |
ptr - 2 | Points two elements backward |
*ptr | Accesses 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
#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:
15
15
15Comparison
| Array indexing | Pointer 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
#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:
12
24
36
48
60Explanation
ptrpoints to the first element.endpoints one position past the final element.The loop continues while
ptris beforeend.*ptrprints 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
#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:
100
200
300
40
50Explanation
*(ptr + 0) = 100updates the first element.*(ptr + 1) = 200updates the second element.*(ptr + 2) = 300updates 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
#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:
10
20
30
40
50Explanation
display()receives an integer pointer and an array size.numbersconverts to a pointer to its first element when passed.The function accesses each element using pointer arithmetic.
The
sizeparameter 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
#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:
Sum: 150Explanation
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
#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:
Largest value: 100The 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
#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:
50 40 30 20 10This 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
#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:
10 20 30
40 50 60Explanation
numbersis 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 rowiand columnj.
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
int numbers[3] = {10, 20, 30};
int (*ptr)[3] = &numbers;Here, ptr points to the entire array of three integers.
Array of pointers
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
| Feature | Pointer to an array | Array of pointers |
|---|---|---|
| Declaration | int (*ptr)[3] | int* ptr[3] |
| Meaning | Points to an entire array | Stores multiple pointers |
| Common use | Multidimensional arrays | Referencing separate variables or objects |
| Structure | One pointer | Array 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
#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:
Array first element: 10
Pointer first element: 10
Array size: 12
Pointer size: 8The sizes shown are system-dependent.
Important differences
| Array | Pointer |
|---|---|
| Stores its elements | Stores an address |
| Has a fixed number of elements | Can point to different objects of a compatible type |
sizeof(array) gives total array storage size | sizeof(pointer) gives pointer size |
| Cannot be reassigned as a whole | Can be reassigned |
| Array name converts to a pointer in many expressions | Pointer 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
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
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
int* first, second;Only first is a pointer. second is an integer.
Solution: Declare each pointer clearly:
int* first;
int* second;16. Best Practices for Pointers With Arrays
Follow these practices when using pointers with arrays:
Initialize pointers before accessing array elements.
Always know the array's size.
Avoid accessing elements outside the array boundaries.
Use
const int*when a function should not modify array elements.Prefer array indexing when it makes the code easier to understand.
Use pointer arithmetic when it makes the intended operation clearer.
Avoid returning pointers to local arrays.
Use standard library containers such as
std::arrayandstd::vectorwhen appropriate.Keep pointer and array lifetimes clear.
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:
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#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 PrepQ: What happens when you subtract two pointers in C++?
Q: Why is pointer decay a potential source of bugs?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
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).