3

## c++兩種不同宣告m*n陣列的方法，記憶體配置差別在哪裡? #保證給最佳解答

``````int ** arr = new int*[m];
for (int i = 0; i < m; i++) {
arr[i] = new int[n];
}
``````

``````int ** arr = new int*[m];
*arr = new int[m * n];
for (int i = 1; i < m; i++) {
*(arr+i) = *(arr+i-1)+n;
}
``````

``````#include <iostream>
using namespace std;

int main()
{
int m =5, n = 6;
int ** arr = new int*[m];
for (int i = 0; i < m; i++) {
arr[i] = new int[n];
}

//將二維陣列給予初始值
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = i+j;
}
}

//印出二維陣列的所有元素
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
``````

``````#include <iostream>
using namespace std;

int main()
{
int m =5, n = 6;
int ** arr = new int*[m];
*arr = new int[m * n];
for (int i = 1; i < m; i++) {
*(arr+i) = *(arr+i-1)+n;
}

//將二維陣列給予初始值
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = i+j;
}
}

//印出二維陣列的所有元素
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
``````

### 1 個回答

4

iT邦大神 1 級 ‧ 2020-05-11 23:03:30