Array Of Pointers

An array of pointers is a fundamental concept in C++ programming that combines the characteristics of arrays and pointers. It allows for the creation of arrays where each element is a pointer to another data type, rather than a directly stored value. This concept is powerful and flexible, enabling dynamic memory allocation, efficient data manipulation, and the creation of complex data structures.

In C++, an array is a collection of elements of the same data type stored in contiguous memory locations. Meanwhile, a pointer is a variable that stores the memory address of another variable. When combined, an array of pointers becomes an array where each element is a pointer, pointing to a memory location where a value of a specific data type is stored.

To understand arrays of pointers better, let’s break down their key components and characteristics:

Declaration: To declare an array of pointers, you specify the data type followed by an asterisk (*) and then the array name with square brackets indicating the size of the array. For example:

int* ptrArray[5];

This declares an array named ptrArray containing five pointers to integers.

Allocation: Unlike a simple array where memory is allocated for the elements directly, an array of pointers requires separate memory allocation for each individual element. This is typically done dynamically using the new keyword or by assigning the address of existing variables. For example:

int* ptr = new int; // Dynamic memory allocation for a single integer
ptrArray[0] = ptr;  // Assigning the pointer to the first element of ptrArray

Initialization: After allocation, you can initialize the pointers in the array by assigning them memory addresses of variables or dynamically allocated memory locations. For example:

int x = 10, y = 20, z = 30;
ptrArray[1] = &x; // Assigning address of variable x to the second element of ptrArray
ptrArray[2] = new int(y); // Dynamically allocating memory for an integer and assigning address to third element

Accessing Elements: Once initialized, you can access the values pointed to by the pointers in the array using pointer dereferencing (*) or manipulate the memory locations directly. For example:

cout << *ptrArray[1]; // Prints the value of variable x
*ptrArray[2] = 25;    // Modifies the value stored at the memory location pointed to by the third element

Dynamic Memory Management: Arrays of pointers are commonly used in scenarios where dynamic memory management is required, such as creating dynamic arrays, linked lists, trees, and other complex data structures. They provide flexibility in memory allocation and deallocation, allowing efficient utilization of memory resources.

The following example gives an introduction to arrays of pointers with a simple C++ program. We’ll create an array of pointers to integers and go through it with explanations:

#include <iostream>

int main() {
    // Declare an array of pointers to integers
    int* ptrArray[3];

    // Declare three integers
    int a = 10, b = 20, c = 30;

    // Assign the addresses of these integers to the pointers in the array
    ptrArray[0] = &a;
    ptrArray[1] = &b;
    ptrArray[2] = &c;

    // Access and print the values using pointers
    std::cout << "Value of a: " << *ptrArray[0] << std::endl;
    std::cout << "Value of b: " << *ptrArray[1] << std::endl;
    std::cout << "Value of c: " << *ptrArray[2] << std::endl;

    return 0;
}
  1. #include <iostream>: This line includes the input/output stream library, allowing us to perform input and output operations.
  2. int main() { ... }: This is the main function, where the execution of the program begins and ends.
  3. int* ptrArray[3];: This line declares an array named ptrArray that holds three pointers to integers. It’s an array of pointers.
  4. int a = 10, b = 20, c = 30;: Here, we declare three integer variables a, b, and c, and initialize them with values 10, 20, and 30 respectively.
  5. ptrArray[0] = &a;, ptrArray[1] = &b;, ptrArray[2] = &c;: These lines assign the addresses of the integer variables a, b, and c to the pointers in the ptrArray.
  6. std::cout << "Value of a: " << *ptrArray[0] << std::endl;: This line prints the value of a by dereferencing the pointer stored in ptrArray[0].
  7. Similarly, std::cout << "Value of b: " << *ptrArray[1] << std::endl; and std::cout << "Value of c: " << *ptrArray[2] << std::endl; print the values of b and c respectively.
  8. return 0;: This statement indicates that the program has executed successfully and returns 0 to the operating system.

Arrays of pointers are a powerful feature in C++ that enable dynamic memory allocation, efficient data manipulation, and the creation of complex data structures. Understanding how to declare, allocate, initialize, and access elements in arrays of pointers is essential for building versatile and efficient C++ programs.

Here are some more examples of Array of Pointers in C++

Array of Pointers to Strings

Introduction: This program demonstrates the concept of an array of pointers to strings. It declares an array of pointers, each pointing to a string, and then prints each string using the pointers.

#include <iostream>

int main() {
    const int size = 3;
    const char *names[size] = {"Alice", "Bob", "Charlie"}; // Array of pointers to strings

    // Print each string using the pointers
    for (int i = 0; i < size; ++i) {
        std::cout << "Name " << i + 1 << ": " << names[i] << std::endl;
    }

    return 0;
}

Explanation:

  • const int size = 3;: Specifies the size of the array of pointers.
  • const char *names[size] = {"Alice", "Bob", "Charlie"};: Declares an array of pointers to constant character strings and initializes them with string literals.
  • for (int i = 0; i < size; ++i) { std::cout << "Name " << i + 1 << ": " << names[i] << std::endl; }: Prints each string using the pointers stored in the array.

This program illustrates the usage of an array of pointers to strings, demonstrating how to store and access strings using pointers.

Array of Pointers to Arrays

Introduction: This program demonstrates the concept of an array of pointers to arrays. It declares an array of pointers, each pointing to a dynamically allocated array of integers, and then prints the values stored in each array using the pointers.

#include <iostream>

int main() {
    const int size = 2;
    int *ptrArray[size]; // Array of pointers to arrays

    // Dynamically allocate memory for arrays and assign pointers to them
    for (int i = 0; i < size; ++i) {
        ptrArray[i] = new int[3]{i, i * 2, i * 3};
    }

    // Print values in each array using the pointers
    for (int i = 0; i < size; ++i) {
        std::cout << "Values in array " << i + 1 << ": ";
        for (int j = 0; j < 3; ++j) {
            std::cout << ptrArray[i][j] << " ";
        }
        std::cout << std::endl;
    }

    // Free dynamically allocated memory
    for (int i = 0; i < size; ++i) {
        delete[] ptrArray[i];
    }

    return 0;
}

Explanation:

  • const int size = 2;: Specifies the size of the array of pointers.
  • int *ptrArray[size];: Declares an array of pointers to integers.
  • for (int i = 0; i < size; ++i) { ptrArray[i] = new int[3]{i, i * 2, i * 3}; }: Dynamically allocates memory for arrays of integers and assigns pointers to them, with each array initialized with values based on i.
  • Nested loop:
    • for (int i = 0; i < size; ++i): Iterates over each pointer in the array.
    • for (int j = 0; j < 3; ++j) { std::cout << ptrArray[i][j] << " "; }: Prints the values in each array using the pointers.
  • for (int i = 0; i < size; ++i) { delete[] ptrArray[i]; }: Frees the dynamically allocated memory.

This program demonstrates the usage of an array of pointers to arrays, showing how to dynamically allocate memory for arrays and store the pointers in an array for accessing and manipulating the arrays.

Array of Pointers to Functions

Introduction: This program demonstrates the concept of an array of pointers to functions. It declares an array of pointers, each pointing to a function with a specific signature, and then calls each function using the pointers.

#include <iostream>

// Functions with specific signatures
void add(int a, int b) {
    std::cout << "Sum: " << (a + b) << std::endl;
}

void subtract(int a, int b) {
    std::cout << "Difference: " << (a - b) << std::endl;
}

void multiply(int a, int b) {
    std::cout << "Product: " << (a * b) << std::endl;
}

int main() {
    const int size = 3;
    void (*ptrArray[size])(int, int) = {add, subtract, multiply}; // Array of pointers to functions

    // Call each function using the pointers
    for (int i = 0; i < size; ++i) {
        std::cout << "Function " << i + 1 << ": ";
        ptrArray[i](10, 5); // Calling function using pointer
    }

    return 0;
}

Explanation:

  • void add(int a, int b), void subtract(int a, int b), void multiply(int a, int b): Define functions with specific signatures.
  • const int size = 3;: Specifies the size of the array of pointers.
  • void (*ptrArray[size])(int, int) = {add, subtract, multiply};: Declares an array of pointers to functions with the specified signatures and initializes them with the addresses of the corresponding functions.
  • for (int i = 0; i < size; ++i) { ptrArray[i](10, 5); }: Calls each function using the pointers in the array with arguments 10 and 5.

This program demonstrates the usage of an array of pointers to functions, showing how to store and call functions using pointers.

Array of Pointers to Objects

Introduction: This program demonstrates the concept of an array of pointers to objects. It declares an array of pointers, each pointing to an object of a class, and then accesses member functions or variables of each object using the pointers.

#include <iostream>

class MyClass {
public:
    MyClass(int val) : value(val) {}
    void display() {
        std::cout << "Value: " << value << std::endl;
    }

private:
    int value;
};

int main() {
    const int size = 2;
    MyClass obj1(10), obj2(20);

    MyClass *ptrArray[size] = {&obj1, &obj2}; // Array of pointers to objects

    // Access member functions or variables of each object using the pointers
    for (int i = 0; i < size; ++i) {
        ptrArray[i]->display();
    }

    return 0;
}

Explanation:

  • class MyClass { ... };: Defines a class MyClass with a member variable value and a member function display.
  • MyClass obj1(10), obj2(20);: Creates two objects of class MyClass with values 10 and 20.
  • const int size = 2;: Specifies the size of the array of pointers.
  • MyClass *ptrArray[size] = {&obj1, &obj2};: Declares an array of pointers to objects of class MyClass and initializes them with the addresses of the objects.
  • for (int i = 0; i < size; ++i) { ptrArray[i]->display(); }: Accesses the display member function of each object using the pointers in the array.

This program demonstrates the usage of an array of pointers to objects, showing how to store and access member functions or variables of objects using pointers.

These examples provide a detailed understanding of arrays of pointers in C++, covering various scenarios from pointers to integers, strings, arrays, functions, and objects.