c++ - 带有初始化器的堆上的多维数组

标签 c++ arrays multidimensional-array malloc new-operator

<分区>

int ** foo()
{
    int ** multiArray = new int*[3];

    int one[3] = { 1, 2, 3 };
    int two[3] = { 4, 5, 6 };
    int three[3] = { 7, 8, 9 };

    multiArray[0] = one;
    multiArray[1] = two;
    multiArray[2] = three;

    return multiArray;
}

返回 multiArray 在上述函数之外工作,但我对内部箭头(一、二、三)的分配方式有所保留。我的第一 react 是它们分配在栈上,而不是堆上。我想要堆。尽管它们以某种方式在该函数之外为我工作,但当我尝试按我应该的方式删除它们时,它失败了。

如果我做这样的事情:

int ** allocatedMultiArray = foo();
int test = allocatedMultiArray[0][2]; // We get 3! Success!
for (int i = 0; i < 8; ++i)
{
     delete[] allocatedMultiArray[i]; // FAILS!
}
delete[] allocatedMultiArray; // WORKS! (If we skip the above for loop of course)

我正在阅读有关多维数组的页面,他特别需要上面的 for 循环来释放 2D 数组(或 3D 数组的附加循环)。但是,回到我的 foo() 等价物,他使用带有循环的 new 运算符手动将数组分配到堆,而不是 { 1, 2, 3 } 初始化数组然后像我一样分配它。 http://www.cplusplus.com/forum/articles/7459/

因此,如果我跳过失败的 for 循环,是否会泄漏内存?我正在做的事情应该有效吗?我真的不想遍历 multiArray,在每个索引上调用 new,然后手动分配每个 int。这只是一个简化的 { 1, 2, 3 },但我有一个从不同函数获得的更复杂的数字集,使用 { } 符号读起来更好。

编辑: 该内部删除的失败是:

Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)

For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.

编辑2: 因此,如果它是未定义的行为,并且没有像我最初认为的那样在堆上分配一、二、三数组,那么如何做如下事情:

int ** foo()
{
    int ** multiArray = new int*[3];
    for(int i = 0; i < 3; ++i)
    {
        multiArray[i] = new int[3];
    }
    multiArray[0] = { 1, 2, 3 }; // Fail "Too many initializer values" on 2
    multiArray[1] = { 4, 5, 6 }; // Fail
    multiArray[2] = { 7, 8, 9 }; // Fail

    return multiArray;
}

编辑 3:不是重复的,因为我特别要求的答案与问题中提供的答案不同,而且我试图确定数组是在堆上还是堆栈上完成的。标记为重复的问题中均未解决这两个问题。事实上,我特别提到了那个问题中投票最多的答案,说它不够。

最佳答案

为了使用 {} 符号在堆上分配数组(仅在 c++11 或更高版本中)

int *a = new int[4]{1,2,3,4};

所以这意味着为了在堆上分配一个多维数组:

int **b = new int*[2]{new int[2]{1,2}, new int[2]{3,4}};

foo 函数应该是:

int ** foo()
{
    int **multiArray = new int*[3]{new int[3]{1,2,3}, new int[3]{4,5,6}, new int[3]{7,8,9}};
    return multiArray;
}

如果您不会使用 c++11,那么就没有简单的方法可以做到这一点。您需要分配内存,然后用值填充它。

关于c++ - 带有初始化器的堆上的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25857323/

相关文章:

c++ - 使用 OSM 数据时路径之间的离线路由断开问题

python - 限制数组上的 scipy.integrate.quad

c# - 在 HTTP POST 中发送数组

php - 用缺少的键填充多维数组

for-loop - for-do 循环结束后获取表值

c++ - 删除原指针后访问weak_ptr

c++ - 调试:跟踪(和区分)同一程序的两个版本的函数调用树

c++ - 从 shared_ptr 获取一个元素

Java - 使用键/值对制作对象?

C++ : Changing the value of a fixed-sized 3D array in a function