C++ Program to Access Elements of an Array Using Pointer
Prerequisites:
A Pointer is a variable that stores the memory location or address of an object or variable. In other words, pointers reference a memory location, and obtaining the value stored at that memory location is known as dereferencing the pointer.
An Array is the collection of homogeneous elements stored in contiguous memory blocks. So, elements in an array can be accessed using a pointer.
Access elements using Pointer
Pointer has the capability to store the address, So, we can store the address of the first element of the array and then traverse the pointer till we reach the end element.
Methods to store the address of the first elements of the array are mentioned below:
- int *ptr = arr;
- int *ptr = &arr[0];
After this, a for loop is used to dereference the pointer and print all the elements and the memory location of the element of the array. At each loop iteration, the pointer points to the next element of the array. Then the array value and address are printed. Let’s check the Pointer to array example.
Example:
C++
#include <iostream>
using namespace std;
int main()
{
int arr[5] = { 6, 2, 5, 7, 4 };
int * ptr = &arr[0];
for ( int i = 0; i < 5; i++) {
cout << "Value of" << i << " arr[" << i << "] is "
<< *(ptr + i) << endl;
cout << "Address of " << *(ptr + i) << " is "
<< ptr + i << endl
<< endl;
}
return 0;
}
|
Output
Value of0 arr[0] is 6
Address of 6 is 0x7ffc9de51fb0
Value of1 arr[1] is 2
Address of 2 is 0x7ffc9de51fb4
Value of2 arr[2] is 5
Address of 5 is 0x7ffc9de51fb8
Value of3 arr[3] is 7
Address of 7 is 0x7ffc9de51fbc
Value of4 arr[4] is 4
Address of 4 is 0x7ffc9de51fc0
Last Updated :
16 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...