数组的相关概念2

1.一维数组的动态分配和内存释放

#include 

using namespace std;

int main()
{
    cout << "Input an array size: ";
    int sizeofarray;
    cin >> sizeofarray;

    //input validity check
    if (sizeofarray <= 0) 
    {
        cout << "Array size must be a positive integer." << endl;
        return 1;
    }

    //dynamic array allocation
    int * arr1 = new int[sizeofarray]; 

    cout << "Input the elements of the array: ";
    for (int i = 0; i < sizeofarray; i++) 
    {
        cin >> arr1[i];
    }

    cout << "Dynamic array elements: " << endl;
    for (int i = 0; i < sizeofarray; i++) 
    {
        cout << arr1[i] << " ";
    }
    cout << endl;

    //free dynamic memory
    delete[] arr1;
    return 0;
}

2. 二维数组的动态分配和内存释放

#include 

using namespace std;

int main()
{
    cout << "Input row and column dimensions: ";
    int row, col;
    cin >> row >> col;

    //validation
    if (row <= 0 || col <= 0) 
    {
        cout << "Dimensions must be positive integers" << endl;
        return 1;
    }

    //memory allocation
    int **arr2 = new int * [row];
    for (int i = 0; i < row; ++i) 
    {
        arr2[i] = new int[col]();    //initialize memory to 0
    }

    //assign a value to an array
    for (int i = 0; i < row; ++i) 
    {
        for (int j = 0; j < col; ++j) 
        {
            arr2[i][j] = i + j + 1; 
        }
    }

    for (int i = 0; i < row; ++i) 
    {
        for (int j = 0; j < col; ++j) 
        {
            cout << arr2[i][j] << " ";    
        }
        cout << endl;    //"\n"换行符
    }

    //memory release
    for (int i = 0; i < row; ++i) 
    {
        delete [] arr2[i];
    }
    delete [] arr2;
    arr2 = NULL; 

    return 0;
}

你可能感兴趣的:(conclusion,c++,学习方法)