搜尋此網誌

[C/C++][不同欄位的動態二維陣列]

要特別注意的是 p 的產生方法,最後 deallocate 可簡單的用剛好可 deallocate 最大 column 數即可,當然也可依每個 row 的不同 column 去 deallocate

/*
* Author: MH
* Since 2013/10/21
* Toolkit: Code::Block 12.11
*/

#include <iostream>

using namespace std;

int main() {
    int i, r=3;

    // generate rows
    int **p = new int *[r];

    // generate columns
    p[0] = new int[1];    // columns for the 1st row
    p[1] = new int[2];    // columns for the 2nd row
    p[2] = new int[3];    // columns for the 3rd row

    // assign values
    p[0][0] = 1;
    p[1][0] = 2;    p[1][1] = 2;
    p[2][0] = 3;    p[2][1] = 3;    p[2][2] = 3;

    // output the value
    cout << p[0][0] << endl;
    cout << p[1][0] << " " << p[1][1] << endl;
    cout << p[2][0] << " "<< p[2][1] << " "<< p[2][2] << endl;

    // deallocate
    for (i=0; i<r; i++) {
        delete []p[i];    // delete columns
    }
    delete []p;

    return 0;

}

沒有留言:

張貼留言