-4

I am writing this c++ code to multiply two 2d matrices and return the resultant 2d matrix.

The error is cannot convert ll (*)[2] to ll**

ll** multiply(ll a[2][2],ll b[2][2])
{
    ll ans[2][2];
    ans[0][0]=((a[0][0]*b[0][0])%mod+(a[0][1]*b[1][0])%mod)%mod;
    ans[0][1]=((a[0][0]*b[0][1])%mod+(a[0][1]*b[1][1])%mod)%mod;
    ans[1][0]=((a[1][0]*b[0][0])%mod+(a[1][1]*b[1][0])%mod)%mod;
    ans[1][1]=((a[1][0]*b[0][1])%mod+(a[1][1]*b[1][1])%mod)%mod;
    return ans;
}
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Divyaanand Sinha
  • 366
  • 1
  • 3
  • 12

1 Answers1

2

You have a fallen into a trap that seems to get a lot of newcomers to the language.

Passing 2D arrays to a function and returning 2D arrays to a function leads to error prone code. Using a strut/class removes those errors.

In your case, since the size of the arrays is fixed, you can easily use a struct

struct MyMatrix
{
   ll data[2][2];
};

then, update multiply to use MyMatrix instead of 2D arrays.

MyMatrix multiply(MyMatrix const& a, MyMatrix const& b)
{
    MyMatrix ans;
    ...
    return ans;
}

You can change the function to an overloaded operator too.

MyMatrix operator*(MyMatrix const& a, MyMatrix const& b)
{
    MyMatrix ans;
    ...
    return ans;
}

and simplify usage to:

MyMatrix a{ fill in the data for a};
MyMatrix b{ fill in the data for b};
MyMatrix c = a*b;
R Sahu
  • 204,454
  • 14
  • 159
  • 270