1

I am trying to pass two dimensional array in function, but is has two errors which I don't know why. I have some articles about passing two dimensional array in function but also can't understand why I fail.

#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) {}
2

1 Answer 1

1

The multidimensional double array matrix you're trying to pass in the function matrixSwap() to the argument double**, actually doesn't represents a multidimensional array.

Use arrays correctly as shown:

#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) {}

Just changed into [][MAXROWS] where MAXROWS contains an unsigned integer of value 5.


The declaration:

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

is equivalent to:

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

Notice that here I've used *matrix and then appended [MAXROWS] which does the same job as matrix[][MAXROWS].

So you may do the same thing in another way as follows:

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;
    }
}

This will give you the output:

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

To see if the matrix is successfully passed into the function by the new argument.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that MAXROWS must be the same as ROWS (and ideally would have the same constant)
@AlanBirtles, yes, the array size must be known to the compiler, variable number of lengths aren't allowed unless you use std::vector<> or use arrays with pointers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.