數組內存的釋放與申請


參考鏈接:https://www.cnblogs.com/usec/p/7413829.html

使用二維數組的時候,有時候事先並不知道數組的大小,因此就需要動態的申請內存。常見的申請內存的方法有兩種: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;

}
復制代碼

注:另一種方法: 

row:行

col:列

unsigned int **ppPathes;

*ppPathes = (unsigned int *)calloc(row * col, sizeof(unsigned int));

使用malloc:

*ppPathes = (unsigned int *)malloc(sizeof(unsigned int )*(PathNumTemp) * (pathLenTemp + 1));


免責聲明!

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



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