stack overflow c++(堆栈溢出 C++)
问题描述
所以我,试图解决一个任务.a 已经有代码,但系统输出,堆栈溢出"我是 C++ 新手,我的英语不好,所以我很抱歉造成误解 =)
So i', trying to solve a task. a already have code, but system outs, "stack overflow" i'm new in c++ and my english isn't good so i'm sorry for misunderstanding =)
#include <iostream>
using namespace std;
int main (){
int n;
int x;
int k = 0; // счетчик для рабочего массива
int a [200000];
scanf("%d
",&n);
for (int i = 0; i< n; ++i){
std::cin >> x;
if (x > 0){
k++;
a[k] = x;
}else if(x == 0){
for (int q = 1; q <= k; ++q){ // копирование
a[k+q] = a[q];
}
k *= 2;
}else{
printf("%d %d
",a[k],k);
k--;
}
}
system("pause");
}
看起来算法工作正常,但唯一的问题是堆栈.非常感谢!
looks like algorithm works correctly, but only problem is stack. thanks a lot!
推荐答案
根本原因:
正如您猜对的那样,堆栈是有限的,并且您的分配似乎足够大,可以通过它来满足.这不是语言语法错误,因此不保证编译错误,但会导致运行时异常,从而导致崩溃.
As you guessed correctly, the stack is limited and seems your allocation is large enough to be catered through it. This is not an language syntax error so it does not warrant a compilation error but it results in a run time exception thus causing a crash.
解决方案 1:
您可以使数组全局化,全局数组的分配不在堆栈上,所以它应该适合您:
You can make the array global, the allocation of an global array is not on stack so it should work fine for you:
int a [200000];
int main()
{
.....
}
解决方案 2:
你可以使用 std::vector
解决方案 3:
您可以通过new
使用动态分配.
You can use dynamic allocation through new
.
这篇关于堆栈溢出 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:堆栈溢出 C++


基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01