c++ dynamically apply for two-dimensional array

1 #include<iostream>
 2  using  namespace std;
 3  int main()
 4  {
 5      int rows= 4 ,cols= 5 ; // Apply for a two-dimensional array with 4 rows and 5 columns 
6      int ** x = new  int *[rows ]; // Use new to apply for rows of int* type space, and then return the first address of this space 
7      for ( int i= 0 ;i<rows;i++ )
 8          x[i] = new  int [cols]; / / Respectively allocate the requested cols int type space to a one-dimensional x pointer array 
 9      // Test code
10     int z=0;
11     for(int i=0;i<rows;i++)//赋值 
12         for(int j=0;j<cols;j++)
13             x[i][j]=z++;
14     for(int i=0;i<rows;i++)//打印 
15     {
16         for(int j=0;j<cols;j++)
17             cout<<x[i][j]<<" ";
18         cout<< endl;
 19      }
 20      // release memory 
21      for ( int i= 0 ;i<rows;i++ )
 22          delete []x[i];
 23      delete []x;
 24      x= 0 ; // avoid user access freed space         
25      return  0 ;
 26 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325076669&siteId=291194637