首页 > 解决方案 > About matrix operations

问题描述

This is a theoretical question, there is no need to show code.

So, I would like to know how to return the result of a sum function, which will add two arrays using pointers.

  1. First, should matrices be declared as a pointer right at the beginning?

  2. So, in the function we will have

void sumMatrix (int ** m) (?)

From here, how to proceed to return the result of this sum, since the matrix itself cannot be returned

标签: cmatrix

解决方案


不可能将任何维度的数组传递给 C 中的函数。甚至无法表达这个概念,因为在大多数情况下,包括函数调用表达式,数组类型的值会自动转换为指针。因此,

  1. 您的函数别无选择,只能以指针的形式接收其参数。

但是,您应该考虑一下具体的指针类型。C 多维数组(例如int arr[3][4])被构造为数组的数组,并且前面提到的自动转换产生指向数组的指针(int (*p)[4]),而不是指向指针的指针。另一方面,您可以构造指针数组 ( int *arr[3]) 并使用与多维数组相同的语法来访问它们。这些到指针的自动转换确实会产生双指针 ( int **p)。尽管访问语法匹配,但这些替代方案在内存布局和访问效率方面却大不相同。

  1. 这取决于。暂时忽略返回总和的问题,您至少有三个不错的选择:
  • void sumMatrix(int r, int c, int **m1, int **m2);这适用于指针数组数据布局。你表达了与 相同的东西
    void sumMatrix(int r, int c, int *m1[], int *m2[]);,我可能会倾向于自己这样做。
  • void sumMatrix(int r, int c, int m1[r][c], int m2[r][c]); 这相当于
    void sumMatrix(int r, int c, int m1[][c], int m2[][c]);
    void sumMatrix(int r, int c, int (*m1)[c], int (*m2)[c]); 这些依赖于 C99 中添加到 C 中的可变长度数组功能,值得知道的是,此功能在 C11 中成为可选。它假设紧凑、高效的数组数组数据布局。
  • void sumMatrix(int r, int c, int *m1, int *m2);或者,等效地,
    void sumMatrix(int r, int c, int m1[], int m2[]);这假设与前面相同的数组数组数据布局,但需要您手动执行索引计算 ( x * c + y)。如果您想要具有可变数组尺寸的数组布局,而不依赖于 VLA,这将很有用。

就个人而言,我倾向于选择数组数组布局和第二个签名选项的变体之一。

从这里开始,如何继续返回这个和的结果,因为矩阵本身无法返回

您仍然有多个选项,但我倾向于添加第五个参数,其类型与第三个和第四个相同,表示结果矩阵。因为,同样,它必须是一个指针,函数写入指向对象的数据将对调用者可见。然后调用者将负责传递指向现有对象的指针,这很方便,因为它允许(但不要求)使用自动分配的对象。

因此,一种完全的可能性是

void sumMatrix(int r, int c, int m1[r][c], int m2[r][c], int result[r][c]) {
    // ...
}

可以这样调用:

int a[3][4], b[3][4], c[3][4];

// ... fill arrays a and b ...

summMatrix(3, 4, a, b, c);
// the result is in matrix c

推荐阅读