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

In C++, arrays are a powerful feature that allows you to store multiple values of the same data type in a single variable.

You can use pointers to access individual elements of an array. In this article, we will show you how to access elements of an array using a pointer in C++.

To get started, you will need to declare an array and a pointer variable.

The array stores the values, and the pointer variable stores the memory address of the first element of the array.

To access the elements of the array, you can use the pointer to refer to the memory location of the array elements.

Here is an example program that demonstrates how to access elements of an array using a pointer:

#include <iostream>

using namespace std;

int main()
{
    int myArray[5] = { 10, 20, 30, 40, 50 };
    int *ptr = myArray; // pointer to the first element of the array

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

    return 0;
}

In this program, we declared an integer array called myArray that has 5 elements.

We then declared a pointer called ptr and assigned it the memory address of the first element of the array using the name of the array.

We used the * operator to declare the pointer.

Next, we used a for loop to iterate through the array elements. Inside the loop, we printed the element number and its value using the pointer.

The *(ptr + i) syntax is used to access the elements of the array using pointer arithmetic.

We added i to the pointer to get the address of each element in the array.

When you run the program, you will get the following output:

Element 0 is 10
Element 1 is 20
Element 2 is 30
Element 3 is 40
Element 4 is 50

As you can see, the program successfully accessed the elements of the array using a pointer.

In conclusion, you can use pointers to access individual elements of an array in C++.

This technique allows you to manipulate the array elements more efficiently and make your code more concise.

We hope this article has helped you to understand how to access elements of an array using a pointer in C++.