Arrays and Pointer Arithmetic
Learn how pointers and arrays are related in this lesson.
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 ...