使用new新建動態二維數組(多注意)


#include<iostream>
using namespace std;
int main()
{
    //設想要建立一個rows行,cols列的矩陣
    //使用new進行新建
    int rows, cols;
    cin >> rows >> cols;
    int **Array = new int*[rows];   //開辟行
    //new
    for (int i = 0; i < rows; i++)
        Array[i] = new int[cols];       //開辟列

    for(int i = 0; i < rows; i++)
        for(int j = 0; j < cols; j++)
            cin >> Array[i][j];
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0;j < cols ; j++)
            cout << Array[i][j];
        cout << endl;
    }
    //delete
    for(int i = 0; i < rows; i++)
        delete [] Array[i];
    delete []Array;
    return 0;
}

對於其它類型的也可以寫成類似的形式,很方便。

參考博客:https://blog.csdn.net/u012027907/article/details/16370625


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM