多维数组的运行时分配 [英] Runtime allocation of multidimensional array

查看:181
本文介绍了多维数组的运行时分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我认为以下语法无效,

So far I thought that the following syntax was invalid,

int B[ydim][xdim];

但是今天我尝试了并且成功了!我运行了很多次以确保它不是偶然的,即使valgrind也没有报告任何 segfault 内存泄漏!我很惊讶它是g ++中引入的新功能吗?我一直使用一维数组来存储矩阵,方法是按照正确的步幅对它们进行索引,如下面程序中的A所示.但是,与B一样,这种新方法是如此简单而优雅,以至于我一直想要.使用真的安全吗?请参阅示例程序.

But today I tried and it worked! I ran it many times to make sure it did not work by chance, even valgrind didn't report any segfault or memory leak!! I am very surprised. Is it a new feature introduced in g++? I always have used 1D arrays to store matrices by indexing them with correct strides as done with A in the program below. But this new method, as with B, is so simple and elegant that I have always wanted. Is it really safe to use? See the sample program.

PS.如果重要的话,我正在用g ++-4.4.3进行编译.

PS. I am compiling it with g++-4.4.3, if that matters.

#include <cstdlib>
#include <iostream>

int test(int ydim, int xdim) {
// Allocate 1D array
    int *A = new int[xdim*ydim](); // with C++ new operator
    // int *A = (int *) malloc(xdim*ydim * sizeof(int)); // or with C style malloc
    if (A == NULL)
        return EXIT_FAILURE;

// Declare a 2D array of variable size
    int B[ydim][xdim];

// populate matrices A and B
    for(int y = 0; y < ydim; y++) {
        for(int x = 0; x < xdim; x++) {
            A[y*xdim + x] = y*xdim + x;
            B[y][x] = y*xdim + x;
        }
    }

// read out matrix A
    for(int y = 0; y < ydim; y++) {
        for(int x = 0; x < xdim; x++)
            std::cout << A[y*xdim + x] << " ";
        std::cout << std::endl;
    }
    std::cout << std::endl;

// read out matrix B
    for(int y = 0; y < ydim; y++) {
        for(int x = 0; x < xdim; x++)
            std::cout << B[y][x] << " ";
        std::cout << std::endl;
    }

    delete []A;
    // free(A); // or in C style
    return EXIT_SUCCESS;
}


int main() {
    return test(5, 8);
}

推荐答案

int b[ydim][xdim]在堆栈上声明一个二维数组 .另一方面,new在堆上分配数组 .

int b[ydim][xdim] is declaring a 2-d array on the stack. new, on the other hand, allocates the array on the heap.

对于任何非平凡的数组大小,将其放在堆上几乎是更好的选择,以免耗尽堆栈空间,或者如果要将数组传递回当前范围之外的东西.

For any non-trivial array size, it's almost certainly better to have it on the heap, lest you run yourself out of stack space, or if you want to pass the array back to something outside the current scope.

这篇关于多维数组的运行时分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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