In C ++ new and delete to create and release a dynamic array
In C ++ programming, then create an array using the new release to delete.
First, create and release a one-dimensional array
#include<iostream> using namespace std; int main () { int n; cin>>n; // assign a dynamic one-dimensional array int *arr=new int[n]; for(int i=0;i<n;i++) cin>>arr[i]; for(int i=0;i<n;i++) cout<<arr[i]<<" "; // release the array arr delete[] arr; return 0; }
Note: [] can not be less behind the delete.
Second, create and release a two-dimensional array
#include<iostream> using namespace std; int main () { int row,col; cin>>row>>col; // allocate space for the row pointer int **arr=new int *[row]; for(int i=0;i<row;i++) arr [i] = new int [col]; // allocate space for each row (each line has elements col) // Enter the number of two-dimensional array for(int i=0;i<row;i++) for(int j=0;j<col;j++) cin>>arr[i][j]; cout<<"*******************"<<endl; // output the number of two-dimensional array for(int i=0;i<row;i++) { for(int j=0;j<col;j++) cout<<arr[i][j]<<" "; cout<<endl; } // release the two-dimensional array (turn) for(int i=0;i<row;i++) delete[] arr[i]; delete[] arr; return 0; }
In C ++ programming, then create an array using the new release to delete.
First, create and release a one-dimensional array
#include<iostream> using namespace std; int main () { int n; cin>>n; // assign a dynamic one-dimensional array int *arr=new int[n]; for(int i=0;i<n;i++) cin>>arr[i]; for(int i=0;i<n;i++) cout<<arr[i]<<" "; // release the array arr delete[] arr; return 0; }
Note: [] can not be less behind the delete.
Second, create and release a two-dimensional array
#include<iostream> using namespace std; int main () { int row,col; cin>>row>>col; // allocate space for the row pointer int **arr=new int *[row]; for(int i=0;i<row;i++) arr [i] = new int [col]; // allocate space for each row (each line has elements col) // Enter the number of two-dimensional array for(int i=0;i<row;i++) for(int j=0;j<col;j++) cin>>arr[i][j]; cout<<"*******************"<<endl; // output the number of two-dimensional array for(int i=0;i<row;i++) { for(int j=0;j<col;j++) cout<<arr[i][j]<<" "; cout<<endl; } // release the two-dimensional array (turn) for(int i=0;i<row;i++) delete[] arr[i]; delete[] arr; return 0; }