C語言/C++ 動態分配數組(一維/二維)的大小

c語言:malloc - free
c++:malloc - free and new - delete

代碼(已通過編譯):

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <deque>
#include <list>
#include <utility>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <bitset>
#include <iterator>
using namespace std;

typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll  INF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double E = exp(1.0);
const int MOD = 1e9+7;
const int MAX = 1e5+5;

int main()
{
    /*
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    */

    /** C語言/C++ */
    /*  一維數組:malloc - free
    int * p;
    int len = 10;// 數組長度
    p = (int *)malloc(len * sizeof(int));
    free(p);
    */

    /* 二維數組:
    int **p;
    int row = 3; int col = 3;
    p = (int **)malloc(row * sizeof(int*));
    for(int i = 0; i < row; i++)
    {
        p[i] = (int *)malloc(col * sizeof(int));
    }
    for(int i = 0; i < row; i++)
    {
        free(p[i]);
    }
    free(p);
    */

    /** C++ */
    /* 一維數組:new - delete
    int * p;
    int len = 10;
    p = new int[len];

    delete []p;
    */

    /* 二維數組:new - delete
    int ** p;
    int row = 3; int col = 3;
    p = new int*[row];
    for(int i = 0; i < row; i++)
    {
        p[i] = new int[col];
    }

    delete []p;
    */

    return 0;
}


























發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章