C - 传递2d数组作为函数参数?

use*_*424 10 c

可以轻松定义一个接受这样的1d array参数的函数:

int MyFunction( const float arr[] )
{    
    // do something here, then return...

    return 1

}
Run Code Online (Sandbox Code Playgroud)

虽然诸如以下的定义 int MyFunction( const float* arr )也可以起作用.

如何定义接受2d array参数的函数?

我知道这有效: int MyFunction( const float** arr )- 但是,是否可以使用第一个使用的变体[]

Jon*_*ler 31

在C99中,您可以在传递之前提供数组的尺寸:

 void array_function(int m, int n, float a[m][n])
 {
      for (int i = 0; i < m; i++)
          for (int j = 0; j < n; j++)
              a[i][j] = 0.0;
 }


 void another_function(void)
 {
     float a1[10][20];
     float a2[15][15];
     array_function(10, 20, a1);
     array_function(15, 15, a2);
 }
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一下,第一个维度实际上是不必要的.它被编译器忽略了. (8认同)

R..*_*R.. 6

尝试这样的事情:

int MyFunction(size_t ncols, const float arr[][ncols])
{    
    // ...
}
Run Code Online (Sandbox Code Playgroud)