C++ dynamic memory space sample of of custom space type size and space length

  • 2020-04-02 02:17:22
  • OfStack

Application demonstration of dynamic memory space

C++ features, the ability to customize the size and length of the space type

The following program is a simple example of array dynamic configuration


#include <iostream>
using namespace std;
int main()
{   int size = 0;
    cout << " Please enter the array length: ";  //Can customize the dynamic application space length
    cin >> size;
    int *arr_Point = new int[size];
    cout << " Specify the element value: " << endl;
    for(int i = 0; i < size; i++)
    {   cout << "arr[" << i << "] = ";
        cin >> *(arr_Point+i);
    }
    cout << " Display element values: " << endl;
    for(int i = 0; i < size; i++)
    {   cout << "arr[" << i << "] = " << *(arr_Point+i)
             << endl;
    }
    delete [] arr_Point;
    return 0;
}

Execution results:


 Please enter the array length: 5
 Specify the element value: 
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
 Display element values: 
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5

Pointers can be used to simulate two-dimensional arrays, as long as the displacement of the index values of two dimensions in a two-dimensional array is clear


#include <iostream>
using namespace std;
int main()
{   int m = 0;
    int n = 0;
    cout << " Input 2d array dimension: ";
    cin >> m >> n;
    int *ptr = new int[m*n];
    for(int i = 0; i < m; i++)
    {   for(int j = 0; j < n; j++)
        {   *(ptr + n*i + j) = i+j;
        }
    }
    for(int i = 0; i < m; i++)
    {   for(int j = 0; j < n; j++)
        {   cout << *(ptr+n*i+j) << "t";
        }
        cout << endl;
    }
    delete [] ptr;
    return 0;
}


Related articles: