C++动态数组

在C中,申请内存使用的是malloc函数;C++中有了更为安全的实现方式——new。

1.一维动态数组的实现

 1 #include <iostream>
 2 
 3 using namespace std;
 4 int main(int argc, char *argv[])
 5 {
 6     int n;    //array size
 7     cin >>n ;
 8     
 9     int *arr = new int[n];
10     for(int i=0;i<n;++i)
11     {
12         cin >>arr[i];
13     } 
14     for(int i=0;i<n;++i)
15     {
16         cout <<arr[i]<<' ';
17     }
18     delete [] arr;
19     return 0;
20 }

2.二维数组的实现

 1 #include <iostream>
 2 using namespace std;
 3 int main(int argc, char *argv[])
 4 {
 5     int col,row;
 6     cin >>row>>col;    //input row number & col number
 7     int **table = new int *[row];
 8     
 9     //construct rows pin
10     for(int i=0;i<row;++i)
11     {
12         table[i] = new int [col];
13     }
14     
15     //input data 
16     for(int i=0;i<row;++i)
17     {
18         for(int j=0;j<col;++j)
19         {
20             cin>>table[i][j]; 
21         }
22     }
23     
24     //output data
25     for(int i=0;i<row;++i)
26     {
27         for(int j=0;j<col;++j)
28         {
29             cout<<table[i][j]<<' '; 
30         }
31         cout <<endl;
32     }
33     
34     //delete all rows pin
35     for(int i=0;i<row;++i)
36     {
37         delete [] table[i];
38     }
39     
40     delete [] table;
41     return 0;
42 }
原文地址:https://www.cnblogs.com/jourluohua/p/8473676.html