堆栈溢出 C++

stack overflow c++(堆栈溢出 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++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)