-3

I'm trying to pass a 2D matrix with dimensions entered by the user to a function, for example arrayTest[r][c]. I've done my research and cannot find an answer that works. I'm using codeblocks on windows if that matters.

My Code:

#include <iostream>

using namespace std;
int r, c;

template <size_t r, size_t c>
void printMatrix(double (&matrix)[r][c])
{
    for(int i=0;i<r;i++)
    {
        for(int j=0;j<c;j++)
        {
             cout<<matrix[i][j]<<" ";
        }
        cout<<endl;
    }
}

int main()
{
    r = 1;
    c = 1;
    double matrix[r][c] = { { } };
    printMatrix(matrix);
    return 0;
}

I currently get the error: no matching function for call printMatrix.

genpfault
  • 47,669
  • 9
  • 68
  • 119
LampPost
  • 101
  • 7

3 Answers3

0

with dimensions entered by the user

double matrix[r][c]

The size of an array variable must be known at compile time, and therefore can not be entered by the user.

However, you can allocate the array dynamically. Dynamic memory management is quite tricky to get right, and it is best to abstract it away in a container object.

There already exists an implementation of dynamic array container in the standard library: std::vector. The type of the elements of the vector is a template argument, so you can use a vector of vectors to represent an array of arrays i.e. a 2D array.

Community
  • 1
  • 1
eerorika
  • 181,943
  • 10
  • 144
  • 256
0

In C++, you should be using std::vector instead of C-style arrays. By the way for your current problem, you can visit here passing 2-d array to a function. Hope it helps. Also you need to input the values of variables r and c before passing (&matrix)[r][c] to the function printMatrix().

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
SSM
  • 84
  • 2
  • 12
0

@user0042 is correct. The best way is to use vectors or another container which removes the need for template that you have created.

using namespace std;
typedef std::vector<std::vector<double>> Double2D;
void printMatrix(Double2D& matrix)
{
    for(int i=0;i<matrix.size();i++)
    {
        for(int j=0;j<matrix[i].size();j++)
        {
             cout<<matrix[i][j]<<" ";
        }
        cout<<endl;
    }
}

int main()
{
    Double2D matrix = { { } }; // fill the matrix here. depending on the compiler you use, you have to use different methods
    printMatrix(matrix);
    return 0;
}
Sam
  • 2,343
  • 3
  • 17
  • 23
  • Using your code, I get two errors: 'vector' in namespace 'std' does not name a template type 'printMatrix' was not declared in this scope Any thoughts? – LampPost Jul 20 '17 at 19:19
  • @LampPost Sorry, the `typedef` above definition of `printMatrix` is missing the ending semicolon. I just edited the post to fix that. – Sam Jul 21 '17 at 20:02