C 中未确定大小的矩阵:如何将它们作为参数传递给函数,如何在我的代码中操作和 return 它们?

Unsized Matrixes in C: how to pass them as an argument to a function, manipulate and return them in my code?

我想知道如何将可变行和列的矩阵传递给函数,在函数内部转换它并在 C 中返回它。

这是我为实现它而尝试构建的代码。

#include <stdio.h>
#include <stdlib.h>


void **f(int **m, int w, int h);

int main()
{
  int A[3][3]={{1,2,3},{4,5, 6},{7,8,9}};
  int B[3][2]={{1,2},{3, 4}, {5, 6}};

  f(A, 3, 3);
  f(B, 3, 2);

  return 0;
}

void **f(int **m, int w, int h )
{
    int i,j;
    int n[w][h];

    for(i=0;i<w;i++)
    {
      for(j=0;j<h;j++)
        n[i][j] = m[i][j] + 1;
        printf("%5d", m[i][j]);
    }
    return 0;
}

编译返回以下错误:

main.c:20:5: warning: passing argument 1 of ‘f’ makes pointer from integer without a cast [->Wint-conversion]
main.c:13:8: note: expected ‘int **’ but argument is of type ‘int’
main.c:21:5: warning: passing argument 1 of ‘f’ makes pointer from integer without a cast [->Wint-conversion]
main.c:13:8: note: expected ‘int **’ but argument is of type ‘int’
Segmentation fault (core dumped)

尽管多维数组长期以来一直是 C 语言中的二等 class 公民,但现代版本为它们提供了更好的支持。如果数组大小包含在函数参数列表中的实际数组之前,它们可以形成该数组的维度。请注意 AB 现在是函数 f():

last 参数
void f(int w, int h, int m[w][h]);

int main()
{
  int A[3][3]={{1,2,3},{4,5, 6},{7,8,9}};
  int B[3][2]={{1,2},{3, 4}, {5, 6}};

  f(3, 3, A);
  f(3, 2, B);

  return 0;
}

void f(int w, int h, int m[w][h])
{
    int n[w][h];

    int i, j;

    for(int i;i<w;i++)
    {
      for(int j;j<h;j++)
        n[i][j] = m[i][j] + 1;
      printf("%5d", m[i][j]);
    }
}

我不记得是哪个版本的 C 引入了这个,但肯定 int **m 参数不正确,因为 m 不是指向指针(或指针数组)的指针。

同样重要的是,此语法不会强制根据参数对数组进行重新排序,因此如果数组在定义时是 [10][3],则它应该是 [10][3]当你将它描述为一个函数时。这是仅用于数组访问的语法糖。