简体   繁体   English

动态2维数组分配

[英]Dynamic 2 dimentional array allocation

I am creating a dynamic 2 dimensional array and allocating it. 我正在创建一个动态二维数组并对其进行分配。 My for loop gives an error after 10-15 runs (not same value everytime) with bad allocation. 我的for循环在分配不正确的情况下运行10-15(每次都不相同)后给出错误。 Any help would be appreciated. 任何帮助,将不胜感激。

__int32 aLarge = 8121432;
__int32 bLarge = 8121784;
ActualPosition** myPositions;

myPositions = new ActualPosition*[aLarge];

for (int x = 0; x < aLarge; x++)
{
    try
    {
        myPositions[x] = new ActualPosition[bLarge];
    }
    catch (bad_alloc& ba)
    {
        // Error here
    }
}

If sizeof(ActualPosition) == 1 then you would need 61,431 GB of memory to hold your array. 如果sizeof(ActualPosition) == 1那么您将需要61,431 GB的内存来保存您的数组。 So you are going to run out of memory unless you have a very large computer. 因此,除非您有一台非常大的计算机,否则您将耗尽内存。

As you tagged you question with C++ and regardless of the memory size issue raised by @NathanOliver, I would suggest using a library container for two-dimensional arrays. 当您用C++标记问题时,无论@NathanOliver引起的内存大小问题如何,我建议对二维数组使用库容器。

For example: 例如:

std::vector<std::vector<ActualPosition>> myArray(aLarge);
for( auto v: myArray )
   v.resize(bLarge);

Accessing elements will be as simple as: 访问元素将非常简单:

myArray[i][j] = somevalue;

without bound checking, or use at() if you want something more safe: 无需边界检查,如果需要更安全的方法,请使用at()

myArray.at(i).at(j) = somevalue;

If the size is known at compile time (which seems to be the case in your code), you can also use std::array . 如果在编译时知道大小(在代码中似乎是这种情况),则也可以使用std::array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM