Application demonstration of dynamic memory space
The ability to customize the type size and length of space using C + + features
The following program is a simple example of a dynamic configuration of arrays
Copy Code code as follows:
#include <iostream>
using namespace Std;
int main ()
{int size = 0;
cout << "Please enter array length:"; Ability to customize the length of dynamic application space
CIN >> size;
int *arr_point = new Int[size];
cout << "Specify element value:" << Endl;
for (int i = 0; i < size; i++)
{cout << "arr[" << i << "] =";
CIN >> * (arr_point+i);
}
cout << "Show element value:" << Endl;
for (int i = 0; i < size; i++)
{cout << "arr[" << i << "] =" << * (Arr_point+i)
<< Endl;
}
delete [] arr_point;
return 0;
}
Execution results:
Copy Code code as follows:
Please enter the array length: 5
Specify element values:
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
You can use pointers to simulate two-dimensional arrays, as long as you know the displacement of the index values of the two dimensions in the two-dimensional array
Copy Code code as follows:
#include <iostream>
using namespace Std;
int main ()
{int m = 0;
int n = 0;
cout << "input two-dimensional array dimension:";
CIN >> m >> N;
int *ptr = new Int[m*n];
for (int i = 0; i < m; i++)
{for (int j = 0; J < N; + +)
{* (ptr + n*i + j) = I+j;
}
}
for (int i = 0; i < m; i++)
{for (int j = 0; J < N; + +)
{cout << * (ptr+n*i+j) << "T";
}
cout << Endl;
}
delete [] ptr;
return 0;
}