像 int a[10][10] 这样分配数组和在 C++ 中使用 new 关键字分配数组有什么区别?
What is the difference between allocating array like int a[10][10] and allocating array using new keyword in c++?
我目前正在使用 Windows 10 和 gcc 版本 6.3.0 (MinGW.org GCC-6.3.0-1).
代码 1
#include <bits/stdc++.h>
using namespace std;
int main(){
int** a = new int*[100000];
for(int i = 0; i < 100000; ++i)
a[i] = new int[1000];
cout << "Array allocation Ok!!!\n";
return 0;
}
//Output
Array allocation Ok!!!
代码 2
#include <bits/stdc++.h>
using namespace std;
int main(){
int arr[100000][1000];
cout << "Array allocation Ok!!!\n";
return 0;
}
//I got no Output, it just return the console back to me
有人建议我区别可能是代码 2 中的行 i 和 i+1 是连续的(行主要表示)即int arr[1000][100]
在内存方面与 int arr[100000]
相同。但在代码 1 中,列条目本质上是连续的,但行不是。但如果情况可能如此,那么 指针算术 呢?
简单的回答就是a[10][10]分配在栈上,new分配的数组分配在堆上。
我目前正在使用 Windows 10 和 gcc 版本 6.3.0 (MinGW.org GCC-6.3.0-1).
代码 1
#include <bits/stdc++.h>
using namespace std;
int main(){
int** a = new int*[100000];
for(int i = 0; i < 100000; ++i)
a[i] = new int[1000];
cout << "Array allocation Ok!!!\n";
return 0;
}
//Output
Array allocation Ok!!!
代码 2
#include <bits/stdc++.h>
using namespace std;
int main(){
int arr[100000][1000];
cout << "Array allocation Ok!!!\n";
return 0;
}
//I got no Output, it just return the console back to me
有人建议我区别可能是代码 2 中的行 i 和 i+1 是连续的(行主要表示)即int arr[1000][100]
在内存方面与 int arr[100000]
相同。但在代码 1 中,列条目本质上是连续的,但行不是。但如果情况可能如此,那么 指针算术 呢?
简单的回答就是a[10][10]分配在栈上,new分配的数组分配在堆上。