码迷,mamicode.com
首页 > 编程语言 > 详细

C++基础:二维数组动态的申请内存和释放内存

时间:2017-08-22 23:07:24      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:delete   for   c++   free   ++   动态开辟   scanf   oid   事先   

使用二维数组的时候,有时候事先并不知道数组的大小,因此就需要动态的申请内存。常见的申请内存的方法有两种:malloc/free 和 new/delete。

一、malloc/free

(1)申请一维数组

void dynamicCreate1Array()
{
    int m;
    int i;
    int *p;

    cout<<("please input the length of data:");
    cin >> m;

    p = (int*)malloc(sizeof(int)*m);//动态开辟  

    cout << "please input data" << endl;
    for (i = 0; i < m; i++)
        cin >> p[i];

    cout << "data is :";
    for (i = 0; i < m; i++)
        cout << p[i] << endl;
    free(p);
}

(2)申请二维数组

void dynamicCreate2Array()
{
    int m, n;
    int i, j;
    int **p;

    printf("please input the row and col:");
    cin >> m >> n;
    //scanf("%d%d", &m, &n);

    p = (int**)malloc(sizeof(int*)*m); //开辟行  

    for (i = 0; i < m; i++)
    {
        *(p + i) = (int*)malloc(sizeof(int)*n);//开辟列  
    }
    //输入数据  
    printf("please input data:");
    for (i = 0; i < m; i++)
        for (j = 0; j < n; j++)
            cin >> p[i][j];
    //输出数据  
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            cout << p[i][j];
        }
        cout << endl;
    }
    //释放开辟的二维空间  
    for (i = 0; i < m; i++)
        free(*(p + i));
}

二、new/delete

(1)申请一维数组

void DynamicCreate1Array()
{
    int len;
    int i;

    cout << "please input the length of data: ";
    cin >> len;

    int *p = new int[len];

    cout << "please input data: ";
    for (int i = 0; i < len; i++)
        cin >> p[i];

    cout << "data is " << endl;
    for (i = 0; i < len; i++)
        cout <<p[i] << endl;

    delete[] p;
}

(2)申请二维数组

void DynamicCreate2Array()
{
    int m, n;
    int i;
    cout << "input row and col: ";
    cin >> m >> n;

    //动态开辟空间  
    int **p = new int*[m]; //开辟行  
    for (int i = 0; i < m; i++)
        p[i] = new int[n]; //开辟列  

    cout << "input data: ";
    for (i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            cin >> p[i][j];

    cout << "output: " << endl;
    for (i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
            cout <<  p[i][j]<<" ";
        cout << endl;
    }

    //释放开辟的资源  
    for (i = 0; i < m; i++)
        delete[] p[i];
    delete[] p;

}

 

C++基础:二维数组动态的申请内存和释放内存

标签:delete   for   c++   free   ++   动态开辟   scanf   oid   事先   

原文地址:http://www.cnblogs.com/usec/p/7413829.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!