TypechoJoeTheme

Yuuuuuu

C++

C/C++如何声明一个长度超过1000000(一百万)的数组

当我在Dev c++里写了类似这样的函数

#include <bits/stdc++.h> 
using namespace std;
int main(){
    int t[1000][1000]={0};    //长度100万
    cout<<t[1];
    return 0;
}

编译器直接崩溃,从头开始一句一句添加,排除了很久,一度怀疑人生。
最后终于发现问题在于中间的int t[1000][1000]={0};那一句。

由于这个数组申明在函数内部,属于局部变量,存放在了栈上,
但是数组占用的内存大小:1000000=1000 x 1000 然后乘以int型数据长度
1000 x 1000 x 4byte 约等于4M,
而栈的默认内存空间为1M左右,所以会导致内存溢出
所以,如果要解决这个问题,可以将数组申明在全局存储区堆上即可

第一种:申明为全局变量

#include <bits/stdc++.h> 
using namespace std;
int t[1000][1000]={0};    //申明为全局变量
int main(){
    cout<<a[1][1];
    return 0;
}

或者第二种(我也不太懂的)方法:
存放在堆上

#include<bits/stdc++.h>
using namespace std;
int main(){
    int *t;
    t = new int[1000][1000];//存放在堆上
    cout<<t[1][1];
    return 0;
}
赞(0)
评论 (0)