【发布时间】:2021-05-11 05:50:44
【问题描述】:
在 C++ 中,当我在函数内声明一个大小为 10^7 的数组时。我无法这样做。但是,当我在全局范围内声明这个具有相同大小的数组时,一切都运行得非常好。我的意思是=> 假设我在函数中声明了数组
void ArrayReturn(){
int N = 1e7+10;
int arr[N]={0}; //When I try to output the content of this array
// there is a blank screen only.
// Now I start performing seive
}
但是,在我全局声明 arr 的同时,输出正常
int arr[10000010];
void ArrayReturn(){
//perform sieve
//output which uses the content of this array, comes fine now.
}
So, I just wanna know whether this issue is because something related to memory assigned to a function over stack is limited, or is there something else that I am missing or don't know at all?
Kindly explain.
【问题讨论】:
-
是的。在堆上分配以解决它(使用
std::vector)。 -
局部变量通常使用进程堆栈来实现。堆栈的大小是有限的,在 Windows 上它只有一个 MiB 大小。
-
根据经验,我倾向于将堆栈上声明的缓冲区大小限制在 1 KB 左右。对于更大的缓冲区,请使用堆。
标签: c++