0

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

int B[ydim][xdim];

但是今天我试过了,它奏效了!我运行了很多次以确保它不会偶然工作,甚至 valgrind 也没有报告任何段错误内存泄漏!我很惊讶。它是 g++ 中引入的新功能吗?我一直使用一维数组来存储矩阵,方法是用正确的步长索引它们,就像在下面的程序中使用 A 所做的那样。但是这个新方法,和B一样,简单优雅,是我一直想要的。使用起来真的安全吗?请参阅示例程序。

PS。如果这很重要,我正在用 g++-4.4.3 编译它。

#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);
}
4

2 回答 2

1

这是一个 C99 的“可变长度数组”或 VLA。如果 g++ 也支持它们,那么我相信它是 C++ 标准的扩展。

不错,不是吗?

于 2010-07-31T04:08:45.193 回答
1

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

对于任何重要的数组大小,几乎可以肯定将它放在堆上会更好,以免您耗尽堆栈空间,或者如果您想将数组传递回当前范围之外的东西。

于 2010-07-31T04:10:07.283 回答