// 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.
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.
CodePudding user response:
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.