简体   繁体   中英

How to pass two-dimensional array to the function so that code would compile

I'm trying to make a program which fill a quadratic matrix with some random values. So here the source code (which works fine):

#include <iostream>
#include <stdlib.h>
#include <iomanip>
using namespace std;
int main()
{
    int const n = 5;
    int matrix[n][n];
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {
            matrix[i][j] = rand()%10;       // fill matrix
            cout<<setw(2)<<matrix[i][j];    // matrix output
        }
        cout<<"\n"; // new line
    }
}

But now I want to rewrite this code using my own function:

#include <iostream>
#include <stdlib.h>
#include <iomanip>
using namespace std;
void fillAndPrintArray (int **matrix, int n); // function prototype
int main()
{
    int const n = 5;
    int matrix[n][n];
    fillAndPrintArray(matrix, n);
}
void fillAndPrintArray(int **matrix, int n)
{
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {
            matrix[i][j] = rand()%10;       // fill matrix 
            cout<<setw(2)<<matrix[i][j];
        }
        cout<<"\n"; // new line
    }
}

But I can't compile this code. I'm getting error:

||In function 'int main()':error: cannot convert 'int (*)[5]' to 'int**' for argument '1' to    'void fillAndPrintArray(int**, int)'.

I don't know how to fix this.

The problem is that you are passing a multidimensional array to a function that takes a pointer to a pointer. In regards to arrays this is a pointer to the first element of an array of pointers, not a two dimensional array.

If you want to pass multidimensional array to a function you can use a template function and take the array by reference.

template<std::size_t U, std::size_t V>
void func(const int (&arr)[U][V])
{
    // do stuff
}

int main()
{
    int arr1[10][10];
    int arr2[15][10];

    func(arr1);
    func(arr2);
}

To do this without a template function just replace U and V with the desired dimensions. for instance to pass a 5x5 array as in your question you would do this.

void func(const int(&arr)[5][5])
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM