Pointer array/Array of pointers

Pointer array/Array of pointers

Sometimes we may want to maintain an array, which can store pointers of int, char or any other data type. A pointer can store one address at a time. So how do we store all element’s respective pointers? This is done using the concept of pointer array. Just like we can declare an array of int, char, float, etc, we can declare an array of pointers.

Array: Array is set of homogeneous elements stored in a contiguous memory location under a single variable name.

Pointer: Pointer is a special variable that stores the address of another variable.

Pointer array:

Array of pointers is an array consisting of pointer variables. It’s declaration syntax is- datatype (*var_name)[size of array]; The values stored inside it are accessed by using “ptr+i” or “ptr[i]”, where ‘ptr’ is name of pointer array and ‘ i ‘ is a variable used to increment.

Let’s take an example for understanding. Consider an array of 5 integer elements. Now to store the address of all elements we create a pointer array of 5 elements. In other words, you can assign 5 pointer variables of type int.

1. Program in C++

#include<iostream>
using namespace std;
int main()
{
    int arr[5],i;
    int (*p)[5];
    p = &arr;
    cout<<"Enter 5 array elements: ";
    for(int i=0;i<5;i++)
        cin>>arr[i];
    cout<<"\nArray Elements\tAddress";
    for(i=0;i<5;i++)
        cout<<"\n\t"<<arr[i]<<"\t"<<p[i];

    return 0;
}

2. Program in C

#include<stdio.h>
int main()
{
    int arr[5],i;
    int (*p)[5];
    p = &arr;
    printf("Enter 5 array elements: ");
    for(i=0;i<5;i++)
    {
        scanf("%d",&arr[i]);
    }

    printf("\nArray Elements\tAddress");
    for(i=0;i<5;i++)
        printf("\n\t%d\t%d",arr[i],p[i]);

    return 0;
}

Output-

Pointer array output

As you can see each element’s address is stored in separate locations. Note that there is a continuous difference between the address of 2 consecutive elements.

Conclusion-

So a pointer array stores the address of the all the elements in an array. We can either create a new array for pointers or use the same array name for pointers. We hope we have cleared this topic. If you have any doubts do tell us in the comment section below. Share it with your friends and programming buddies. Also tell us what other programs you would like us to post.

For more such content follow us on Instagram. Visit again!

ErrorFreeProgram.

3 COMMENTS

comments user
n95 masks

I like this and found it useful.

    comments user
    ErrorFreeProgram

    We are glad you find it useful!

Leave a Reply

Your email address will not be published. Required fields are marked *