Unlocking the Power of Pointers in C++
Understanding Pointers and Arrays
In C++, pointers are variables that hold the addresses of other variables. But what makes them truly powerful is their ability to store the addresses of cells in an array. Let’s dive into an example to see how this works.
Imagine we have an integer array arr
and a pointer variable ptr
. We can store the address of the first element of the array in ptr
using the code ptr = arr;
. Notice that we didn’t use &arr[0]
, because both are equivalent. This means we can also use ptr
to access the addresses of the rest of the array elements using &arr[1]
, &arr[2]
, and so on.
Pointing to Every Array Element
But what if we need to point to a specific element in the array using the same pointer ptr
? Let’s say we want to point to the fourth element. If ptr
points to the first element, then ptr + 3
will point to the fourth element. We can access the elements using the single pointer, and the address between ptr
and ptr + 1
differs by the size of the data type. For example, if ptr
is a pointer to an int
data type, the address difference is 4 bytes in a 64-bit operating system.
Example 1: C++ Pointers and Arrays
Let’s see this in action:
“`
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;
cout << “Addresses of array elements:” << endl;
cout << &arr[0] << endl;
cout << &arr[1] << endl;
cout << &arr[2] << endl;
cout << &arr[3] << endl;
cout << &arr[4] << endl;
cout << “Using pointer ptr:” << endl;
cout << ptr << endl;
cout << ptr + 1 << endl;
cout << ptr + 2 << endl;
cout << ptr + 3 << endl;
cout << ptr + 4 << endl;
“
ptr`.
The output shows that we can access the addresses of the array elements using the pointer
Array Names as Pointers
In most contexts, array names decay to pointers. This means we can use pointers to access elements of arrays. However, it’s essential to remember that pointers and arrays are not the same. There are a few cases where array names don’t decay to pointers.
Example 2: Array Name Used as Pointer
Let’s see an example where we use the array name as a pointer:
“`
int arr[5];
for (int i = 0; i < 5; i++) {
cin >> *(arr + i);
}
for (int i = 0; i < 5; i++) {
cout << *(arr + i) << endl;
}
“
arr
In this example, we use the array nameas a pointer to store and display the values entered by the user. We haven't declared a separate pointer variable, but rather used the array name
arrfor the pointer notation. This is possible because the array name
arr` points to the first element of the array, making it act like a pointer.