数组申明在函数内部,属于局部变量,存放在了栈上, 看看数组占用的内存大小:1000000=1000*1000然后乘以int型数据长度 1000*1000*4byte约等于4M, 而栈的默认内存空间为1M左右,所以会导致内存溢出 解决这个问题,可以将数组申明在全局存储区或堆上即可 方法一:申明为全局变量方法二:存放在堆上
方法一:申明为全局变量
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#include<iostream>
#include<algorithm>
using
namespace
std;
int
list[1000000];
//全局变量
int
main(){
int
a,b;
cin>>a;
for
(b=0;b<a;b++)
cin>>list[b];
sort(list,list+a);
for
(b=0;b<a;b++)
cout<<list[b]<<endl;
return
0;
}
|
方法二:存放在堆上
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include<iostream>
#include<algorithm>
using
namespace
std;
int
main(){
int
a,b,*list;
//int list[1000000];
list =
new
int
[1000000];
//存放在堆上
cin>>a;
for
(b=0;b<a;b++)
cin>>list[b];
sort(list,list+a);
for
(b=0;b<a;b++)
cout<<list[b]<<endl;
return
0;
}
|

本文探讨了在函数内部声明大型数组导致栈内存溢出的问题,并提供了两种解决方案:一是将数组声明为全局变量;二是将数组分配在堆上。通过示例代码详细展示了这两种方法的具体实现。
2755

被折叠的 条评论
为什么被折叠?



