C++二維數組的動態聲明


int **a  =  new int* [m]   //分配一個指針數組,將其首地址保存在a中   、

for(int i = 0; i < m; i++)   //為指針數組的每個元素分配一個數組

       a[i] = new int [n];

相當於產生了一個二維數組 a[m][n]了

靜態聲明的數組可以有公式(假設也是m行n列)

                                          b[i][j] = b[i*n +j]

這是因為數組b是連續的一片內存,而動態聲明的數組任意的a[k]都是一個int*類型,即一個地址,所以只能a[i][j]或者*(*(a+i) + j)來訪問數組的元素,而不能a[i*n + j]使用。

動態聲明的數組,使用后需要釋放內存。

for(int i = 0; i < m; ++i)

      delete []a[i];

delete []a;

 1 #include <iostream>
 2 #include <stdlib.h>
 3 
 4 using namespace std;
 5 
 6 
 7 int main()
 8 {
 9     int row,column;
10     cin >> row >> column;
11     //申請空間
12     int **a =  new int* [row];    
13     for(int i = 0; i < row; i++)
14         a[i] = new int[column];
15 
16     //使用空間
17     for(int j = 0; j < row; j++)
18         for(int k = 0; k < column; k++)
19             a[j][k] = rand() % 100;
20     
21     for(int j = 0; j < row; j++)
22     {
23         cout << endl;
24         for(int k = 0; k < column; k++)
25             cout << a[j][k] << " ";
26     }
27     //釋放空間
28     for(int i = 0; i < row; i++)
29         delete []a[i];
30     a = NULL;
31 
32     return 0;
33 }

 

 1  //方法二,利用vector創建二維數組
 2 #include <iostream>
 3 #include <stdlib.h>
 4 
 5 using namespace std;
 6 
 7 
 8 {  
 9     int row,column;  
10     cin>>row>>column;  
11   13     //申請空間  
14     vector<vector<int> > a(row,vector<int>(column));  
15       
16   
17     //使用空間  
18     for(int j = 0;j < row;j++)  
19         for(int k = 0;k< column;k++)  
20             a[j][k] = rand()%100;  
21   
22     for(int j = 0;j < row;j++)  
23     {  
24         cout<<endl;  
25         for(int k = 0;k< column;k++)  
26         {  
27             a[j][k] = rand()%100;  
28             cout<<a[j][k]<<"     ";  
29         }  
30     }         
31     return 0;       
32 }  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM