簡體   English   中英

如何使用 C++ 中的指針動態分配和釋放二維數組?

[英]How to dynamically allocate and deallocate a 2D array using pointers in c++?

我想使用指針動態分配然后解除分配一個二維數組。 我的想法是創建一個指向指針數組的指針,其中每個指針指向一個 int,這就是我想要的方式。 這些函數是 bool 類型,因為無論操作是否成功,我都想返回一個布爾值。

問題是deallocateTwoDimTable函數不返回 bool,所以它似乎根本不起作用。 如果我不使用int** table = nullptr; 但是讓它未初始化int** table ,然后我收到錯誤(在解除分配時)我想要釋放的內存尚未初始化。

如果我將參數int **table更改為int **&table ,代碼確實有效,但我想這意味着通過引用而不是使用指針傳遞。 我如何使它工作? 非常感謝所有幫助:)

這是我的主要方法:

int main() {
    int** table = nullptr;
        
    int sizeX = 5; // rows
    int sizeY = 3; // columns
    
    bool allocationResult = allocateTwoDimTable(table, sizeX, sizeY);
    cout << endl << "allocation result: " << (allocationResult ? "true" : "false") << endl;
    
    bool deallocationResult = deallocateTwoDimTable(table, sizeX);
    cout << endl << "deallocation result: " << (deallocationResult ? "true" : "false");
}

分配功能:

bool allocateTwoDimTable(int **table, int sizeX, int sizeY) {
    if (sizeX <= 0 || sizeY <= 0) return false;

    // allocate 2D table
    table = new int*[sizeX];
    for(int i = 0; i < sizeX; i++) {
        table[i] = new int[sizeY];
    }

    cout << endl << "Table " << sizeX << " x " << sizeY << endl;
    for(int i = 0; i < sizeX; i++) {
        cout << endl;
        for(int j = 0; j < sizeY; j++) {
            cout << table[i][j] << ", ";
        }
    }

    return true;
}

解除分配功能:

bool deallocateTwoDimTable(int **table, int sizeX) {
    if(sizeX <= 0) return false;

    for (int k = 0; k < sizeX; k++) {
        delete[] table[k];
    }

    delete[] table;

    return true;
}

您必須通過引用傳遞指針。 否則,函數allocateTwoDimTable 將處理原始指針值的副本。 也就是說,改變副本不會影響原始指針。

此外,參數sizeXsizeY應該具有size_t類型,因為通常類型int可能無法指定所需的數組維度。

該函數可以聲明為

bool allocateTwoDimTable( int ** &table, size_t sizeX, size_t sizeY);

注意你創建的是未初始化的數組

table[i] = new int[sizeY]

所以輸出它們

cout << table[i][j] << ", ";

調用未定義的行為。

當需要傳遞引用或指針時,有機會時,最好通過引用傳遞。

指針可以接受空參數,引用不能,使用更安全,除非出於某種原因,您特別需要傳遞空參數,我認為情況並非如此。

請注意,打印數組時您正在訪問未初始化的內存。

另請注意,盡管使用布爾標志來表示分配錯誤,但您的代碼仍然容易受到攻擊,更好的方法是使用std::exception

bool allocateTwoDimTable(int** &table, int sizeX, int sizeY) {
    if (sizeX <= 0 || sizeY <= 0) return false;

    // allocate 2D table
    table = new int* [sizeX];
    
    for (int i = 0; i < sizeX; i++) {
        table[i] = new int[sizeY];
    }

    cout << endl << "Table " << sizeX << " x " << sizeY << endl;
    for (int i = 0; i < sizeX; i++) {
        cout << endl;
        for (int j = 0; j < sizeY; j++) {
            table[i][j] = i + j; //initializing elements of the array
            cout << table[i][j] << ", ";
        }
    }

    return true;
}
bool deallocateTwoDimTable(int (** &table), int sizeX) {
    if (sizeX <= 0) return false;

    for (int k = 0; k < sizeX; k++) {
        delete[] table[k];
    }

    delete[] table;

    return true;
}
int main() {

    int** table = nullptr;

    const int sizeX = 5; // rows
    const int sizeY = 3; // columns

    try {    
        const bool allocationResult = allocateTwoDimTable(table, sizeX, sizeY);
        cout << endl << "allocation result: " << (allocationResult ? "true" : "false") << endl;

        const bool deallocationResult = deallocateTwoDimTable(table, sizeX);
        cout << endl << "deallocation result: " << (deallocationResult ? "true" : "false");
    }
    catch (std::exception& e)
    {
        std::cout << e.what();
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

看看這個答案https://stackoverflow.com/a/936709/9936992他們還提到了使用模擬兩個 D 陣列的單個陣列的可能性

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM