Runtime allocation of multidimensional array

别说谁变了你拦得住时间么 提交于 2020-01-06 06:09:41

问题


So far I thought that the following syntax was invalid,

int B[ydim][xdim];

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. 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);
}

回答1:


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.




回答2:


This is a C99 'variable length array' or VLA. If they are supported by g++ too, then I believe it is an extension of the C++ standard.

Nice, aren't they?



来源:https://stackoverflow.com/questions/3376740/runtime-allocation-of-multidimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!