Array of Pointers in C++

 Array of Pointers 


Basic Concept

An array where each element is a pointer (not a normal variable).

Each element holds the address of another variable (or object).


Example 1: Array of Integer Pointers

#include <iostream>

using namespace std;

 

int main() {

    int a = 10, b = 20, c = 30;

 

    // Declare an array of 3 int pointers

    int *arr[3];

 

    // Assign addresses to pointers

    arr[0] = &a;

    arr[1] = &b;

    arr[2] = &c;

 

    // Access values using the dereference operator

    for (int i = 0; i < 3; i++) {

        cout << "Value of element " << i << " = " << *arr[i] << endl;

    }

 

    return 0;

}


Output:

Value of element 0 = 10

Value of element 1 = 20

Value of element 2 = 30


Memory Structure

Array Index

Stored Value (Address)

Dereferenced Value

arr[0]

Address of a

10

arr[1]

Address of b

20

arr[2]

Address of c

30

Each element of arr stores the address of an integer variable.


 

Array of Pointers to Strings (Character Arrays)

An array of pointers to char is often used to store a list of strings.

 

Example 2:

#include <iostream>

using namespace std;

 

int main() {

    // Array of pointers to char

    const char *names[] = {"Alice", "Bob", "Charlie", "David"};

 

    for (int i = 0; i < 4; i++) {

        cout << names[i] << endl;

    }

 

    return 0;

}


Output:

Alice

Bob

Charlie

David

Here,


 Array of Pointers vs Pointer to Array

Concept

Declaration

Meaning

Array of Pointers

int *arr[5];

arr is an array containing 5 pointers to int

Pointer to Array

int (*ptr)[5];

ptr is a pointer that points to an array of 5 ints


 

Dynamic Array of Pointers

Dynamically allocate memory to each pointer inside the array.

 

Example :

#include <iostream>

using namespace std;

 

int main() {

    int *arr[3]; // Array of 3 pointers

 

    // Allocate memory dynamically

    for (int i = 0; i < 3; i++) {

        arr[i] = new int;              // Each arr[i] points to a new integer

        *arr[i] = (i + 1) * 10;

    }

 

    // Print values

    for (int i = 0; i < 3; i++) {

        cout << *arr[i] << " ";

    }

 

    // Free memory

    for (int i = 0; i < 3; i++) {

        delete arr[i];

    }

 

    return 0;

}


Output:

10 20 30


 

Example: 2D Array using an Array of Pointers

#include <iostream>

using namespace std;

 

int main() {

    int row1[] = {1, 2, 3};

    int row2[] = {4, 5};

    int row3[] = {6, 7, 8, 9};

 

    int *arr[] = {row1, row2, row3};

 

    cout << arr[0][1] << endl; // 2

    cout << arr[1][0] << endl; // 4

    cout << arr[2][3] << endl; // 9

 

    return 0;

}

 

Output:

2

4

9

====================================================================

Post a Comment

0 Comments