溫馨提示×

C++動態(tài)二維數(shù)組如何傳遞給函數(shù)

c++
小樊
84
2024-07-25 16:53:16
欄目: 編程語言

在C++中,可以通過指針或引用的方式將動態(tài)二維數(shù)組傳遞給函數(shù)。

  1. 使用指針傳遞動態(tài)二維數(shù)組:
void function(int** array, int rows, int cols) {
    // 訪問數(shù)組元素
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            cout << array[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {
    int rows = 3;
    int cols = 3;
    
    // 創(chuàng)建動態(tài)二維數(shù)組
    int** arr = new int*[rows];
    for(int i = 0; i < rows; i++) {
        arr[i] = new int[cols];
    }
    
    // 初始化數(shù)組
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            arr[i][j] = i * rows + j;
        }
    }
    
    // 調(diào)用函數(shù)
    function(arr, rows, cols);
    
    // 釋放內(nèi)存
    for(int i = 0; i < rows; i++) {
        delete[] arr[i];
    }
    delete[] arr;
    
    return 0;
}
  1. 使用引用傳遞動態(tài)二維數(shù)組:
void function(int**& array, int rows, int cols) {
    // 訪問數(shù)組元素
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            cout << array[i][j] << " ";
        }
        cout << endl;
    }
}

int main() {
    int rows = 3;
    int cols = 3;
    
    // 創(chuàng)建動態(tài)二維數(shù)組
    int** arr = new int*[rows];
    for(int i = 0; i < rows; i++) {
        arr[i] = new int[cols];
    }
    
    // 初始化數(shù)組
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            arr[i][j] = i * rows + j;
        }
    }
    
    // 調(diào)用函數(shù)
    function(arr, rows, cols);
    
    // 釋放內(nèi)存
    for(int i = 0; i < rows; i++) {
        delete[] arr[i];
    }
    delete[] arr;
    
    return 0;
}

無論是使用指針還是引用,都可以在函數(shù)中對動態(tài)二維數(shù)組進(jìn)行操作。需要注意的是,在傳遞動態(tài)二維數(shù)組給函數(shù)后,需要在函數(shù)結(jié)束后手動釋放內(nèi)存,以避免內(nèi)存泄漏。

0