C++ Tutorial C++ Advanced C++ Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

C++ - Passing an array to a function



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. Please 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 called MyArray and array of pointers called p are created. p is assigned the address of MyArray using address-of (&) operator to create array of pointers.

#include <iostream>
using namespace std;
 
int main (){
  int MyArray[5] = {100, 200, 300, 400, 500};
  int *p[5];
    
  for(int i = 0; i<5; i++) {
    p[i] = &MyArray[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. Please see the example below:

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

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

The output of the above code will be:

0x7ffd023e3f50
0x7ffd023e3f58
0x7ffd023e3f60
Blue
Red
Green

❮ C++ - Arrays

5