array of Pointer in C++ is a Examples of Array and Pointer based on two different concept of C++, are follows
what is an Array of pointers in c++?
in simple terms, declare an array as pointer type of variable, are called Array of Pointer or collection of pointer called array of pointer in C++.
an array of pointer is a collection of each element addresses,
Let’s explore it,
when pointing a normal variable we use,
int *ptr;
int x;
*ptr = x;
while in Array of Pointer,
int *ptr[4]
int arr[4] = {3,2,4,1};
*ptr = arr
now ptr points all arr variable Elements,
when we declare an array as pointer type of variable so pointer variable points each element of that array, that means we can manipulate each element using these elements’ address.
while, access these address’s value, we use *ptr[0]*ptr[1],*ptr[2],*ptr[3].
while accessing these elements address, ptr[0], ptr[1], ptr[2], ptr[3] will be used.
The array of Pointer is the collection of address which store the array of elements.
Thus, each element of the array become pointer type elements. now we can say, The collection of Pointer is called Array of Pointer.
let’s consider this without a pointer before going for Array of Pointer,
array of pointers program in C++
#include<iostream>
using namespace std;
int main()
{
int i,arr[4] = {3,2,4,1,};
cout<<"\n Elements are:\n";
for(i= 0; i<4; i++)
{
cout<<"arr["<<i<<"]= "arr[i]<<" "; //displaying elements
}
return 0;
}
OUTPUT
Elements are:
arr[0]= 3
arr[1]= 2
arr[2]= 4
arr[3]= 1
declaration of Array of Pointer in C++
using an array of pointer we can store int or other data types to a pointer array, here is the syntax of an array pointer declaration,
data type *array_name[size];
The data-type can be of any type. Let’s consider with an example of int data type,
Example
int *ptr[4];
int arr[4] = {3,2,4,1};
Here ptr is an array type of pointer which will store the int value of array variable by assigning each element address to it.you can understand this through the program given below-
#include<iostream>
using namespace std;
int main()
{
int *ptr[4];
int i,arr[4] = {3,2,4,1};
clrscr();
for(i= 0; i<4; i++)
{
ptr[i] = &arr[i]; //assigning each elements address in ptr[i]
cout<<"address of value "<<arr[i]<<" is "<<ptr[i]<<endl;
}
cout<<"\n Elements are:\n";
for(i= 0; i<4; i++)
{
cout<<*ptr[i]<<" "; //displaying elements
}
return 0;
}
OUTPUT
address of value 3 is 0x8f2bff8e
address of value 2 is 0x8f2bff90
address of value 4 is 0x8f2bff92
address of value 1 is 0x8f2bff94
Elements are:
3 2 4 1
As we know, we can access an array element from index value i.e.
ptr[0] = &arr[0]; address of 3 in ptr[0]
ptr[1] = &arr[1]; address of 2 in ptr[1]
ptr[2] = &arr[2]; address of 4 in ptr[2]
ptr[3] = &arr[3]; address of 1 in ptr[3]
now accessing elements from this pointer variable we use,
*ptr[0] = 3
*ptr[1] = 2
*ptr[2] = 4
*ptr[3] = 1
more about pointer
Previous-Pointer in C++