Arrays and Pointer Arithmetic
Learn how pointers and arrays are related.
We'll cover the following...
In C++, arrays and pointers are closely related. They share a fundamental connection in how they handle data and memory.
Array name a pointer?
The name of an array in C++ acts as a pointer to its first element. This means that an array name can be used as a pointer to the type of the array’s elements. However, this pointer is constant; you cannot change it to point to another address.
int arr[5] = {10, 20, 30, 40, 50};int* ptr = arr; // ptr points to the first element of arr
In the above code, we create an array of 5
elements. Here, arr
is essentially a constant pointer to arr[0]
. Then, we create an int
pointer and initialize it with the array. By doing this, this pointer ptr
can be used to iterate through the array elements using pointer arithmetic.
As stated above, the array name as a pointer is a constant and cannot be reassigned. For example, running the following command will give an error.
arr = ptr; // Error: Cannot assign a new address to the array name
Iterating arrays using pointers
We can traverse through the array elements using pointers. Incrementing a pointer moves it to the next element in the array. Let’s look at the following code:
# include <iostream>using namespace std;int main (){int arr[5] = {10, 20, 30, 40, 50};int* ptr = arr; // ptr points to the first element of arrfor (int i = 0; i < 5; i++) {cout << *(ptr + i) << " "; // Outputs each element in arr}return 0;}
Here, we create an array of 5
elements and an int
pointer. We initialize this pointer with the array, and then we use this pointer to iterate through the array. The ...