C++ Tutorial C++ Advanced C++ References

C++ - Array of Pointers



An array of pointers is defined as the same way as an array. The declaration starts with datatype pointed to by the pointer followed by * and name of the array of pointers with size enclosed in square brackets. See the syntax below:

Syntax

//integer datatype array of pointer
//with name p and size 5.
int *p[5];

Example:

In the example below, an array of pointers is created. By using address-of (&) operator, it is then used to hold the address of each elements of an array of type int.

#include <iostream>
using namespace std;
 
int main (){
  int Arr[5] = {100, 200, 300, 400, 500};
  int *p[5];

  for(int i = 0; i<5; i++) {
    p[i] = &Arr[i];
  }

  for(int i = 0; i<5; i++) {
    cout<<*p[i]<<"\n";
  }
  return 0;
}

The output of the above code will be:

100
200
300
400
500

Example:

An array of pointers to character can also be used to store a list of strings. See the example below:

#include <iostream>
using namespace std;
 
int main (){
  const char *p[3] = {"Blue", "Red", "Green"};
    
  //see memory locations
  cout<<"Memory locations are:\n";
  for(int i = 0; i<3; i++)  {
    cout<<p+i<<"\n";
  }

  //see values stored
  cout<<"\nValues stored are:\n";
  for(int i = 0; i<3; i++) {
    cout<<*(p+i)<<"\n";
  }
  return 0;
}

The output of the above code will be:

Memory locations are:
0x7ffdd9bb5440
0x7ffdd9bb5448
0x7ffdd9bb5450

Values stored are:
Blue
Red
Green

❮ C++ - Pointers