堆栈溢出 C++ [英] stack overflow c++

查看:47
本文介绍了堆栈溢出 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++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆