H.G H.G - 1 month ago 7
C++ Question

can't pass by reference a pointer returned from a function

why I need intermediate variable to pass my return pointer by reference instead of just using the function that returns that pointer ?

This doesn't compile

int main ()
{
testfunc(getpointer());
return 0;
}



error: C2664: 'void testfunc(int *&)': cannot convert argument 1 from 'int *' to 'int *&'


and this compiles

int main ()
{
int *i = getpointer();
testfunc(i);
return 0;
}


my two functions

void testfunc(int *& i) // I have to use this interface
{
cout << i[0] <<endl;
}

int* getpointer()
{
int * arr1 = new int[1];
arr1[0]=10;
return arr1;
}

Answer

The C++ language prohibits binding a non-const reference to a temporary. In this case, the simple fix is to make testfunc take a const reference to an int*.