2012-07-15 66 views
3

我想在一个函数内部处理一个扁平的一维数组,因为它是一个3D数组。我知道我可以使用宏来这样的翻译坐标:为什么函数调用中的变量数组长度在C中可能,但在C++中不可以?

#define f3d(x,y,z,nx,ny) ((z)*(nx)*(ny) + (y)*(nx) + (x)) 

但我的老师告诉我有一个办法简单地投下他们在函数调用。 所以下面的测试程序可以正常使用良好,编译器拨打电话:gcc -std=c99 -o test.exe main.c

的main.c:

#include <stdlib.h> 
#include <stdio.h> 
static void init(int n, double a[n][n][n]){ 
    for(int i=0; i<n; i++) 
    for(int j=0; j<n; j++) 
     for(int k=0; k<n; k++) 
     a[i][j][k] = i; 
} 

int main(int argc, char **argv){ 
    int n = 5; 
    double *a = malloc(n*n*n*sizeof(*a)); 
    init(n, (double (*)[n][n])a); 
    for(int i=0; i<n*n*n; i++)printf("%lf ",a[i]);  
    return 0; 
} 

但现在我必须使用C++和我不能编译:g++ -o test.exe main.c 编译器说: error: array bound is not an integer constant 我可以想象为什么编译器与变量arraylengths斗争,但为什么它在C中工作?

有人可以告诉我为什么吗?

是否有解决此问题的解决方法?

在此先感谢!

更新: 非常感谢答案,但现在我很困惑。我使用g ++(SUSE Linux)4.4.1 [gcc-4_4-branch revision 150839],它应该能够使用VLA。为什么它不编译和抛出“错误:数组绑定不是一个整数常量”?

+4

C支持VLAS; C++没有。我相信有人会拿出这个证明来标准化。 – chris 2012-07-15 02:48:12

+1

C++的解决方案是使用STL向量而不是 – paulsm4 2012-07-15 02:58:36

+0

不知道是否应答或注释,但是这个代码在C中是非法的.a应该被声明为'double(* a)[n] [n]'。您不允许将指针转换为double的指针,以指向double数组的数组。 – Vality 2014-08-15 12:49:23

回答

2

从GCC:

http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the brace-level is exited. ...

You can also use variable-length arrays as arguments to functions:

struct entry 
tester (int len, char data[len][len]) 
{ 
    /* ... */ 
} 
+0

该代码没有“可变长度自动数组”,它有一个“指向可变长度数组”类型的指针。 – 2012-07-15 02:57:00

+0

也是C11的可选功能。 – Aesthete 2012-07-15 03:00:24

相关问题