溫馨提示×

C++動態二維數組如何傳遞給函數

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

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

  1. 使用指針傳遞動態二維數組:
void function(int** array, int rows, int cols) {
    // 訪問數組元素
    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;
    
    // 創建動態二維數組
    int** arr = new int*[rows];
    for(int i = 0; i < rows; i++) {
        arr[i] = new int[cols];
    }
    
    // 初始化數組
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            arr[i][j] = i * rows + j;
        }
    }
    
    // 調用函數
    function(arr, rows, cols);
    
    // 釋放內存
    for(int i = 0; i < rows; i++) {
        delete[] arr[i];
    }
    delete[] arr;
    
    return 0;
}
  1. 使用引用傳遞動態二維數組:
void function(int**& array, int rows, int cols) {
    // 訪問數組元素
    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;
    
    // 創建動態二維數組
    int** arr = new int*[rows];
    for(int i = 0; i < rows; i++) {
        arr[i] = new int[cols];
    }
    
    // 初始化數組
    for(int i = 0; i < rows; i++) {
        for(int j = 0; j < cols; j++) {
            arr[i][j] = i * rows + j;
        }
    }
    
    // 調用函數
    function(arr, rows, cols);
    
    // 釋放內存
    for(int i = 0; i < rows; i++) {
        delete[] arr[i];
    }
    delete[] arr;
    
    return 0;
}

無論是使用指針還是引用,都可以在函數中對動態二維數組進行操作。需要注意的是,在傳遞動態二維數組給函數后,需要在函數結束后手動釋放內存,以避免內存泄漏。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女