Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing Arrays as Parameters and Returning Them in C++

// createArray_1 returns the array as a return value
double* createArray_1( ) {
    return new double [ 10 ];
}

// createArray_2 returns the array from the parameter list
// (using a reference parameter)
void createArray_2( double*& arr ) {
    arr = new double [ 10 ];
}

// createArray_3 returns the array from the parameter list
// (without using a reference parameter but simulating
// pass-by-reference using a pointer)
void createArray_3( double** arr ) {
    *arr = new double [ 10 ];
}

// What is wrong with the following two functions?
// void incorrectCreateArray_1( double* arr ) {
// arr = new double [ 10 ];
//}
// double* incorrectCreateArray_2( ) {
// double arr[ 10 ];
// return arr;
// }

And we have the main function:

int main() {
   double* D;
   D = createArray_1();
   delete [] D;
   createArray_2( D );
   delete [] D;
   createArray_3( &D );
   delete [] D;
   return 0;
}

Can you help me understand why create_array2 and create_array3 are correct whereas incorrectCreateArray_1 and incorrectCreateArray_2 are wrong?

To me, incorrectCreateArray_1 should be fine because we are passing a pointer, and then assign a double array of size 10 to it, which seems correct.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

On the other hand, incorrectArray_2 returns a double pointer, which should be fine because arr points to a double array, which also seems correct.

>Solution :

void incorrectCreateArray_1( double* arr ) 
{
    arr = new double [ 10 ];
}

is incorrect because you receive a pointer (uninitialized) and you make it point somewhere else. But only the arr pointer, local to this function, gets changed. The calling code still keeps its (uninitialized) pointer.

double* incorrectCreateArray_2( ) 
{
    double arr[ 10 ];
    return arr;
}

is incorrect because you return a pointer to a local object (arr) which will not be valid to access after the function returns.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading