// 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;
// }
我們有主要功能:
int main() {
double* D;
D = createArray_1();
delete [] D;
createArray_2( D );
delete [] D;
createArray_3( &D );
delete [] D;
return 0;
}
你能幫我理解為什么 create_array2 和 create_array3 是正確的,而 wrongCreateArray_1 和 wrongCreateArray_2 是錯誤的嗎?
對我來說,不正確的CreateArray_1 應該沒問題,因為我們正在傳遞一個指標,然后為其分配一個大小為 10 的雙精度陣列,這似乎是正確的。
另一方面,correctArray_2 回傳一個雙精度指標,這應該沒問題,因為 arr 指向一個雙精度陣列,這似乎也是正確的。
uj5u.com熱心網友回復:
void incorrectCreateArray_1( double* arr )
{
arr = new double [ 10 ];
}
是不正確的,因為您收到一個指標(未初始化)并且您將它指向其他地方。但是只有arr這個函式本地的指標被改變了。呼叫代碼仍然保留其(未初始化的)指標。
double* incorrectCreateArray_2( )
{
double arr[ 10 ];
return arr;
}
是不正確的,因為您回傳了一個指向本地物件 ( arr) 的指標,該指標在函式回傳后將無法訪問。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/516835.html
標籤:C 数组指针删除运算符
上一篇:C結構指標型別相同但仍然失敗
下一篇:不使用指標訪問結構體陣列屬性
