new delete

动态分配内存,类似于malloc/free

看一下如何使用

整形

    int *p = new int;
    *p = 5;

或者在new的同时直接初始化

    int *p = new int(5);
delete p;

字符

    char *p = new char('a');
    delete p;

数组

int *p = new int[5];
delete []p

二维数组:

网上有资料这样new二维数组: int **p = new int[4][5]; 这个方法是错误的 int[4][5]这个数据类型和 **p并不匹配

我们可以这样做

    int **p = new int*[4];
    for (auto i = 0; i < 4; i++)
    {
        p[i] = new int[5];
    }

或者直接用向量

    vector<vector<int>> p(4);
    p[1].push_back(4);
    p[1].push_back(6);
    p[2].push_back(1);
    cout<<p[1][1]<<endl;

猜你喜欢

转载自www.cnblogs.com/qifeng1024/p/12652002.html