barej
barej

Reputation: 1406

C++ passing 2D array to constructor (no known conversion error)

I am writing a program that handles matrices. The program enables you to enter the matrix at calling of the constructor:

CMatrix A(3,3,{{1,2,3},{4,5,6},{7,8,9}});

But it seams that there is a problem with sending a 2d array as int** to the constructor. How can I fix it? I would prefer to avoid template if possible. I am also looking for a clean way.

The following code faces with error:

error: no matching function for call to ‘CMatrix::CMatrix(int, int, <brace-enclosed initializer list>)’ CMatrix A(3,3,{{1,2,3},{4,5,6},{7,8,9}});

,

 note:   no known conversion for argument 3 from ‘<brace-enclosed initializer list>’ to ‘int**’

code:

#include <iostream>
using namespace std;

class CMatrix
{
    int rows,columns;
    int **members;
public:
    CMatrix(int rows,int columns);
    CMatrix(int rows,int columns,int **clone);
};

CMatrix::CMatrix(int rows,int columns)
{
    this->rows=rows;
    this->columns=columns;
    members=new int*[rows];
    for(int i=0;i<columns;i++)
        members[i]=new int[columns];
}

CMatrix::CMatrix(int rows,int columns,int **clone)
{
    CMatrix(rows,columns);
    for(int i=0;i<rows;i++)
        for(int j=0;j<columns;j++)
            members[i][j]=clone[i][j];
}

int main()
{
    CMatrix A(3,3,{{1,2,3},{4,5,6},{7,8,9}});
    ...
    return 0;
}

calling:

g++ -std=c++11 test.cpp

Upvotes: 3

Views: 2749

Answers (1)

dconman
dconman

Reputation: 90

Array initializers of the form { ... } can only be used to initialize an array. eg

int myArray[] = {1,2,3,4};

To pass in your array to your constructor, you must first build it. Either by building each row manually:

int row1[] = {1,2,3};
int row2[] = {4,5,6};
int row3[] = {7,8,9};
int * matrix[] = {row1, row2, row3};
CMatrix(3,3,matrix);

Or by dynamically building the whole thing:

int rows = 3;
int cols = 3;
int ** matrix = new int*[rows]; // allocate array of int pointers
for( int i = 0; i < rows; i++)
{
    matrix[i] = new int*[cols]; // allocate each array of ints
}
for (int i = 0; i<(rows*cols); i++)
{
    matrix[i/cols][i%cols] = i; //or whatever you need to set it to
}

CMatrix(rows,cols,matrix); // make your call

for( int i = 0; i < rows; i++)
{
    delete[] matrix[i]; //delete each int array
}
delete[] matrix; //delete matrix

You can immediately delete the matrix because CMatrix copies the values, not the array.

Upvotes: 2

Related Questions