有很多类似的问题,但我仍然找不到任何与C99/C11中可变长度数组特征相关的答案.
如何将多维可变长度数组传递给C99/C11中的函数?
例如:
void foo(int n, int arr[][]) // <-- error here, how to fix?
{
}
void bar(int n)
{
int arr[n][n];
foo(n, arr);
}
Run Code Online (Sandbox Code Playgroud)
编译器(g++-4.7 -std=gnu++11)说:
error: declaration of ‘arr’ as multidimensional array must have bounds for all dimensions except the first
如果我改成它int *arr[],编译器仍抱怨:
error: cannot convert ‘int (*)[(((sizetype)(((ssizetype)n) + -1)) + 1)]’ to ‘int**’ for argument ‘2’ to ‘void foo(int, int**)’
下一个问题,如何通过值传递它以及如何通过引用传递它?显然,通常你不希望在将它传递给函数时复制整个数组.
对于常量长度数组,它很简单,因为正如"常量"所暗示的那样,在声明函数时应该知道长度:
void foo2(int n, int arr[][10]) // <-- ok …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个C99程序,我有一个隐式定义的字符串数组:
char *stuff[] = {"hello","pie","deadbeef"};
Run Code Online (Sandbox Code Playgroud)
由于未定义数组维度,因此为每个字符串分配了多少内存?是否所有字符串都分配了与定义中最大字符串相同数量的元素?例如,以下代码是否等同于上面的隐式定义:
char stuff[3][9];
strcpy(stuff[0], "hello");
strcpy(stuff[1], "pie");
strcpy(stuff[2], "deadbeef");
Run Code Online (Sandbox Code Playgroud)
或者每个字符串只分配了它在定义时所需的内存量(即stuff[0]包含6个元素stuff[1]的数组,包含4个元素stuff[2]的数组,并包含9个元素的数组)?