C++ Program to Access Elements of an Array Using Pointer


Pointers store the memory location or address of variables. In other words, pointers reference a memory location and obtaining the value stored at that memory location is known as dereferencing the pointer.

A program that uses pointers to access a single element of an array is given as follows −

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int arr[5] = {5, 2, 9, 4, 1};
   int *ptr = &arr[2];
   cout<<"The value in the second index of the array is: "<< *ptr;
   return 0;
}

Output

The value in the second index of the array is: 9

In the above program, the pointer ptr stores the address of the element at the third index in the array i.e 9.

This is shown in the following code snippet.

int *ptr = &arr[2];

The pointer is dereferenced and the value 9 is displayed by using the indirection (*) operator. This is demonstrated as follows.

cout<<"The value in the second index of the array is: "<< *ptr;

Another program in which a single pointer is used to access all the elements of the array is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int arr[5] = {1, 2, 3, 4, 5};
   int *ptr = &arr[0];
   cout<<"The values in the array are: ";
   for(int i = 0; i < 5; i++) {
      cout<< *ptr <<" ";
      ptr++;
   }
   return 0;
}

Output

The values in the array are: 1 2 3 4 5

In the above program, the pointer ptr stores the address of the first element of the array. This is done as follows.

int *ptr = &arr[0];

After this, a for loop is used to dereference the pointer and print all the elements in the array. The pointer is incremented in each iteration of the loop i.e at each loop iteration, the pointer points to the next element of the array. Then that array value is printed. This can be seen in the following code snippet.

for(int i = 0; i < 5; i++) {
   cout<< *ptr <<" ";
   ptr++;
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 24-Jun-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements