我是 C 语言新手,有 Java 背景。
我遇到了无法编译的问题,因为编译器想在编译时知道数组的大小。例如,我想将我的数组打印到控制台。它不允许我这样声明函数原型(prototype):
void printRoom(char[][], int, int); //not allowed
我该怎么办?难道就没有办法解决这个问题吗?我发现的在线资源似乎表明,如果我想使用函数原型(prototype),我必须知道尺寸。看来它还要求函数头也具有数组的大小。
void printRoom(char room[][], int height, int width){ // not allowed, missing array bounds
此问题的有效解决方案是否只是说数组大小为 1000*1000(我可以预期的最大数组大小)?这对我来说似乎很草率,但我很确定只要我保持在数组实际大小的范围内,它就会起作用。
目前我对指针和 malloc 不感兴趣。
最佳答案
如果编译器支持可变长度数组,那么您可以通过以下方式声明函数
void printRoom( int, int, char[*][*]);
或者只是
void printRoom( int, int, char[][*]);
这是一个演示程序
#include <stdio.h>
#include <string.h>
void printRoom( int, int, char[*][*]);
void printRoom( int m, int n, char a[m][n] )
{
for ( int i = 0; i < m; i++ )
{
printf( "%3s ", a[i] );
putchar( ' ');
}
printf( "\n" );
}
int main(void)
{
const int M = 2;
const int N = 10;
char a[M][N];
strcpy( a[0], "Hello" ),
strcpy( a[1], "World" );
printRoom( M, N, a );
return 0;
}
它的输出是
Hello World
如果编译器不支持 VLA,则列数必须是常量。例如
#define N 100
//...
void printRoom(char[][N], int, int);
关于c - 以多维数组作为参数的函数原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41884801/