堆栈溢出 C++

编程入门 行业动态 更新时间:2024-10-24 01:49:46
本文介绍了堆栈溢出 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++

本文发布于:2023-11-09 09:54:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572074.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:堆栈

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!