Array of Pointers

Array of Pointers Program in C++

IntermediateTopic: Memory Management Programs
Back

C++ Array of Pointers Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 20, c = 30, d = 40, e = 50;
    
    // Array of pointers
    int* arr[5] = {&a, &b, &c, &d, &e};
    
    cout << "Array of pointers:" << endl;
    for (int i = 0; i < 5; i++) {
        cout << "arr[" << i << "] = " << arr[i] 
             << " points to value: " << *arr[i] << endl;
    }
    
    // Modify values through array of pointers
    *arr[0] = 100;
    *arr[1] = 200;
    
    cout << "\nAfter modification:" << endl;
    cout << "a = " << a << ", b = " << b << endl;
    cout << "*arr[0] = " << *arr[0] << ", *arr[1] = " << *arr[1] << endl;
    
    // Array of pointers to strings
    const char* names[] = {"Alice", "Bob", "Charlie", "David", "Eve"};
    
    cout << "\nArray of pointers to strings:" << endl;
    for (int i = 0; i < 5; i++) {
        cout << "names[" << i << "] = " << names[i] << endl;
    }
    
    return 0;
}
Output
Array of pointers:
arr[0] = 0x7fff5fbff6ac points to value: 10
arr[1] = 0x7fff5fbff6a8 points to value: 20
arr[2] = 0x7fff5fbff6a4 points to value: 30
arr[3] = 0x7fff5fbff6a0 points to value: 40
arr[4] = 0x7fff5fbff69c points to value: 50

After modification:
a = 100, b = 200
*arr[0] = 100, *arr[1] = 200

Array of pointers to strings:
names[0] = Alice
names[1] = Bob
names[2] = Charlie
names[3] = David
names[4] = Eve

Understanding Array of Pointers

An array of pointers is an array where each element is a pointer. This is useful for: 1) Storing addresses of different variables, 2) Creating arrays of strings (each string is a pointer to char array), 3) Dynamic memory allocation, 4) Implementing data structures like trees. It allows efficient access and modification of multiple variables through a single array.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents