c-plus-plus
  1. c-plus-plus-array-of-pointers

C++ Pointers: Array of Pointers

Syntax

data_type *pointer_name[size];

where,

  • data_type: Type of data to be stored in pointer
  • pointer_name: Name of the pointer
  • size: Size of the array

Example

#include <iostream>
using namespace std;

int main() {
   int a = 10, b = 20, c = 30;
   int *ptr[3] = { &a, &b, &c };

   for (int i = 0; i < 3; i++) {
      cout << "Value of ptr[" << i << "] = " << *ptr[i] << endl;
   }

   return 0;
}

Output

Value of ptr[0] = 10
Value of ptr[1] = 20
Value of ptr[2] = 30

Explanation

The above program demonstrates the use of an array of pointers. Here, an integer array of size 3 is created, and each element is used to store the address of an integer variable. This array of pointers can be used to access and manipulate the values of the variables whose addresses are stored in the pointers.

Use

An array of pointers can be used to:

  • Store the addresses of multiple variables of the same data type
  • Access and manipulate the values of the variables whose addresses are stored in the pointers
  • Pass multiple pointers to a function

Important Points

  • An array of pointers is an array of memory addresses, where each element of the array is a pointer to a data type.
  • The size of the array determines the number of pointers that can be stored in the array.
  • Each element of the array can be used to store the address of a variable of the same data type.

Summary

An array of pointers is a powerful tool for accessing and manipulating multiple variables of the same data type. It can help in writing efficient code by reducing the number of variables that need to be created and maintained. By understanding the syntax and usage of an array of pointers, you can take your programming skills to the next level.

Published on: