先來看兩者的做法:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#define R_SIZE 4//row_size | |
#define C_SIZE 4//column_size | |
using namespace std; | |
int main() | |
{ | |
int a[R_SIZE][C_SIZE];/*宣告二維陣列*/ | |
for(int i = 0; i < R_SIZE; i++)//給值 | |
for(int j = 0; j < C_SIZE; j++) | |
a[i][j] = j; | |
for(int i = 0; i < R_SIZE; i++)//輸出測試 | |
{ | |
for(int j = 0; j < C_SIZE; j++) | |
cout << a[i][j] << " "; | |
cout << endl; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#define R_SIZE 4//row_size | |
#define C_SIZE 4//column_size | |
using namespace std; | |
int main() | |
{ | |
/*創造動態二維陣列*/ | |
int **a; | |
a = new int*[R_SIZE]; | |
for(int i = 0; i < R_SIZE; i++) | |
a[i] = new int[C_SIZE]; | |
/*完成*/ | |
for(int i = 0; i < R_SIZE; i++)//給值 | |
for(int j = 0; j < C_SIZE; j++) | |
a[i][j] = j; | |
for(int i = 0; i < R_SIZE; i++)//輸出測試 | |
{ | |
for(int j = 0; j < C_SIZE; j++) | |
cout << a[i][j] << " "; | |
cout << endl; | |
} | |
} |
接下來是參數傳遞的方式:
靜態:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void pass_2d_array(int (*ptr)[C_SIZE]); |
動態:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void pass_2d_array(int **ptr); |
動態二維陣列的參數傳遞很簡單,就是把雙重指標傳過去而已。但是靜態二維陣列的就比較奇怪一點,我們知道靜態二維陣列的概念和動態的有點像,用上面那張動態二維陣列示意圖來理解靜態二維陣列是沒有什麼太大問題的,但在傳遞參數時就不能傳遞雙重指標了。原因是實際上在記憶體中,靜態二維陣列並不是長這個樣子,而是第二個整數一維陣列的開頭與第一個的尾巴緊緊相連,老師在教靜態陣列時說的重點:"陣列是在主記憶體中一塊連續的空間,用來儲存相同型態的資料",靜態二維陣列也是如此,所以如果人眼看的見靜態二維陣列的話,我們會覺得他是一維的。因此,在傳遞靜態二維陣列的時候用 (int*)[column_size],必須給他 column_size,他才知道這個二維陣列長什麼樣子。反過來看,動態二維陣列傳遞的時候也不能用 (int*)[column_size],因為它的每個一維陣列在記憶體中都是各自分開的,只是用指標接在一起。做法比較複雜的動態二維陣列,反而長得跟我們想像中的比較相近。
沒有留言:
張貼留言