【问题标题】:Pass two dimensional array in function [duplicate]在函数中传递二维数组[重复]
【发布时间】:2020-06-23 06:25:37
【问题描述】:

我试图在函数中传递二维数组,但是有两个我不知道为什么的错误。我有一些关于在函数中传递二维数组的文章,但也无法理解为什么我会失败。

#include <iostream>

using namespace std;

// prototypes
void matrixSwap(double** matrix, int rows, int columns);

int main()
{
    const int ROWS = 5;
    const int COLUMNS = 5;

    double matrix[ROWS][COLUMNS] =
    {
      { 1,  2,  3,  4,  5},
      { 6,  7,  8,  9,  0},
      {11, 12, 13, 14, 15},
      {16, 17, 18, 19, 20},
      {21, 22, 23, 24, 25}
    };

    matrixSwap(matrix, ROWS, COLUMNS);
    /* it says
       1) argument of type "double (*)[5U]" is incompatible with parameter of type "double **"
       2) 'void matrixSwap(double *[],int,int)': cannot convert argument 1 from 'double [5][5]' to 'double *[]'
    */
}

void matrixSwap(double** matrix, int rows, int columns) {}

【问题讨论】:

标签: c++ arrays pointers


【解决方案1】:

您试图将函数matrixSwap() 传递给参数double** 的多维double 数组matrix,实际上并不代表多维数组。

如图所示正确使用数组:

#include <iostream>

using namespace std;

const unsigned short MAXROWS = 5;

// prototypes
void matrixSwap(double matrix[][MAXROWS], int rows, int columns);

int main()
{
    const int ROWS = 5;
    const int COLUMNS = 5;

    double matrix[ROWS][COLUMNS] =
    {
      { 1,  2,  3,  4,  5},
      { 6,  7,  8,  9,  0},
      {11, 12, 13, 14, 15},
      {16, 17, 18, 19, 20},
      {21, 22, 23, 24, 25}
    };

    matrixSwap(matrix, ROWS, COLUMNS);
}

void matrixSwap(double matrix[][MAXROWS], int rows, int columns) {}

刚刚更改为[][MAXROWS],其中MAXROWS 包含一个值为5 的无符号整数。


声明:

void matrixSwap(double matrix[][MAXROWS], int rows, int columns)

相当于:

void matrixSwap(double (*matrix)[MAXROWS], int rows, int columns)

请注意,我在这里使用了*matrix,然后附加了[MAXROWS],它的作用与matrix[][MAXROWS] 相同。

所以你可以用另一种方式做同样的事情,如下所示:

void matrixSwap(double (*matrix)[MAXROWS], int rows, int columns) {
    for (int i = 0; i < columns; i++) {
        for (int j = 0; j < rows; j++) {
            std::cout << matrix[i][j] << ' ';
        }
        std::cout << std::endl;
    }
}

这将为您提供输出:

1 2 3 4 5 
6 7 8 9 0
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25

查看matrix是否通过新参数成功传递给函数。

【讨论】:

  • 请注意MAXROWS 必须与ROWS 相同(理想情况下应具有相同的常量)
  • @AlanBirtles,是的,编译器必须知道数组大小,除非您使用 std::vector&lt;&gt; 或使用带指针的数组,否则不允许使用可变长度。
猜你喜欢
  • 2013-01-18
  • 2013-03-28
  • 1970-01-01
  • 2013-05-12
  • 2021-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
相关资源
最近更新 更多