Search code examples
c++c++14

reference to an array of pointers


How do I write a reference to an-array-of-pointers as a parameter to a function?

Class B - works. array of integers.

Class A - fails. array of pointers to integers.

#include <iostream>

int a = 1;
int b = 2;
int arr[2] = { 1, 2 } ;
int * parr[2] = { &a, &b };

class B // works
{
  int * parr_;
  B(int (&arr)[2] ) 
  {
     parr_ =  arr;
  }
};

class A // doesn't work!
{
  int ** pparr_;
  A(int (*&pparr)[2] ) 
  {
     pparr_ =  pparr;  //error 
      
  }
  
};

The error:

ERROR!
g++ /tmp/K0oKZ2yIsn.cpp
/tmp/K0oKZ2yIsn.cpp: In constructor 'A::A(int (*&)[2])':
/tmp/K0oKZ2yIsn.cpp:25:16: error: cannot convert 'int (*)[2]' to 'int**' in assignment
   25 |      pparr_ =  pparr;
      |                ^~~~~
      |                |
      |                int (*)[2]

Solution

  • You need to change int (*&pparr)[2] to int *(&pparr)[2] as explained below.


    The problem is that currently pparr is a reference to a pointer to an array of size 2 with elements of type int. What you actually wanted(as per your description) is to declare pparr as an reference to an array of pointer to int which can be done by changing the declaration of pparr to as shown below.

    class A // works now
    {
      int ** pparr_;
    //------v------------------->note the asterisk is moved outside the parenthesis
      A(int *(&pparr)[2] )  //now pparr is a reference to an array of size two with elements of type int*
      {
         pparr_ =  pparr;  //works now
          
      }
      
    };
    

    Working demo