到目前为止,我认为以下语法无效,
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);
}