Print Array Values using Pointer and Array in C++


This program demonstrates the use of an array of pointers in C++.

  • It first declares an integer array ptr1 of size 5 and an array of integer pointers ptr2 of size 5. It then uses a for loop to read in 5 integer values from the user and store them in the ptr1 array.
  • Another for loop is then used to assign the addresses of each element of ptr1 to the corresponding element of ptr2. This is achieved using the address-of operator &ab;.
  • Finally, another for loop is used to print the values of the integers stored in ptr1 by dereferencing the pointers in ptr2.

Note that the use of an array of pointers can be helpful in certain situations, such as when dealing with arrays of arrays or arrays of strings, as it allows for more flexible memory management.

Source Code

#include<iostream>
using namespace std;
int main()
{
   int ptr1[5];
   int *ptr2[5];
   std::cout<<"Enter five numbers :"<<std::endl;
   for(int i=0;i<5;i++)
   {
    std::cin>>ptr1[i];
   }
   for(int i=0;i<5;i++)
   {
    ptr2[i]=&ptr1[i];
   }
   std::cout<<"The values are"<<std::endl;
   for(int i=0;i<5;i++)
   {
    std::cout<<*ptr2[i]<<std::endl;
   }
   return 0;
}
To download raw file Click Here

Output

Enter five numbers :34
12
31
54
23
The values are
34
12
31
54
23



Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples