声明多维数组时的堆栈溢出异常 [英] Stack Overflow Exception when declaring multidimensional arrays

查看:73
本文介绍了声明多维数组时的堆栈溢出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一般对编程还是有些陌生,但是在声明3D和4D数组时遇到了一个问题.在主函数的开头,我有几个这样的声明,但是我将问题缩小到了这四个:

I'm somewhat new to programming in general and I've run into an issue with declaring 3D and 4D arrays. I have several declarations like this at the start of my main function, but I've narrowed the problem down to these 4:

string  reg_perm_mark_name[64][64][64];
short   reg_perm_mark_node_idex[64][64][64];
short   reg_perm_mark_rot[64][64][64][4];
short   reg_perm_mark_trans[64][64][64][3];

当我使用它们运行程序时,我的可执行文件中出现"System.StackOverflowException".我更希望有一种动态分配它们的方法,无论如何我现在拥有的方法都是临时的,而且我不确定如何正确地声明数组指针.

When I run my program with these, I get "System.StackOverflowException" in my executable. I would much prefer a way to allocate them dynamically, The way I have it now was meant to be temporary anyway and I'm not sure how to declare array pointers properly.

例如,我在4D数组reg_perm_mark_trans中使用的4个元素是[节点索引] [区域索引] [标记索引] [xyz坐标].此外,一次总共声明了35个多维数组. (其中大多数是1D和2D),我不确定是否有帮助.

The 4 elements I'm using in the 4D array reg_perm_mark_trans, for example, are [node index][region index][marker index][xyz coordinates]. Also there's a total of 35 multidimensional arrays being declared at once. (most of them are 1D and 2D) I'm not sure if that helps.

有人可以告诉我如何使这些4d数组起作用,或者如何使它们通过指针或向量动态分配吗?请描述一下,我还在学习.

Can someone show me how to make these 4d arrays work or maybe how to make them dynamically allocating with pointers or vectors? Be descriptive please, I'm still learning.

推荐答案

为简单起见,假设sizeof(string) == 2(可能更多),您试图在堆栈上分配(64 ^ 3)* 9 * 2个字节.总计4,718,592字节,约合4.5 MiB.最有可能的是,您的堆栈上没有4.5 MiB.

Assuming for simplicity that sizeof(string) == 2 (it's probably more), you're trying to allocate (64^3)*9*2 bytes on the stack. That comes out to 4,718,592 bytes, or approximately 4.5 MiB. Most likely, you just don't have 4.5 MiB available on your stack.

由于这些变量是在main()中声明的,因此您有两种可能的解决方案:

Since these variables are declared in main(), you have two possible solutions:

  1. 声明它们为static.

main()外部将它们声明为全局变量.

Declare them outside main(), as global variables.

这将导致它们在程序启动之前分配,而不是在堆栈上分配.两种方法之间的唯一区别是它们是否将在其他功能中可见.

This will cause them to be allocated before the program starts, rather than on the stack. The only difference between the two approaches is whether they'll be visible in other functions.

也许还有一种方法可以告诉您的编译器该程序需要更多的堆栈空间,但是我认为将它们设为静态可能是更好的解决方案.如果它们不是main()的函数,则可能需要做其他事情.

There may also be a way to tell your compiler that the program needs more stack space, but I think making them static is probably the better solution here. If they were in a function other than main() though, you'd probably need to do something else.

这篇关于声明多维数组时的堆栈溢出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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