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++
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
