C++ Pointers and arrays
Pointers and arrays are notions that are related in C++. The initial element of an array can actually be thought of as a pointer. This means that the array’s name can be used as a pointer to the array’s first element.
Example:
#include <iostream>
using namespace std;
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr;
ptr = arr;
for (int i = 0; i < 5; i++) {
cout << "Element " << i << " is " << *(ptr + i) << endl;
}
return 0;
}
Output:
Element 0 is 1
Element 1 is 2
Element 2 is 3
Element 3 is 4
Element 4 is 5
This example declares and initialises a 5-dimensional integer array named arr with some values. Moreover, an integer pointer ptr is declared.
The pointer ptr is given the address of the first element of the array arr by the statement ptr = arr. This is similar to ptr = &arr[0], since arr is considered as a pointer to its first element.
The for loop then use pointer arithmetic to cycle through the array’s elements. The formula *(ptr + I dereferences the pointer ptr that has been increased by I and returns the value for the ith array index.
This example demonstrates how an array can be treated as a pointer and how pointer arithmetic can be used to iterate over the elements of the array.