0

I'm trying to multiply to n**x**n dynamic matrices and returning it's result. This is the code for it:

long long int** Multiply(long long int** m1, long long int **m2)
{
    static long long int** output;
    output= new long long int* [k];

    for (int i=0; i<k; i++)
        output[k]= new long long int [k];

    long long int cellRes= 0;
    for (int i=0; i<k; i++)
    {
        for (int f=0; f<k; f++)
        {
            for (int j=0; j<k; j++)
            {
                cellRes+= m1[i][j]*m2[j][f];
            }
            output[i][f]= cellRes;
            cellRes=0;
        }
    }

    return output;
}

It seems to do it well at returning the new matrix, but for some reason the program is crashing after executing Multiply()... Even if I create a new matrix, allocate it and then assign Multiply() to it, it crashes.

I can't figure out what I'm doing wrong. Any idea?

BlastDV
  • 143
  • 5
  • Why is output static? Use `vector>` – Neil Kirk Sep 22 '14 at 19:26
  • I read somewhere that I had to declare it static in order to avoid to reference a non existing memory position.. This is where I got that from: http://www.tutorialspoint.com/cplusplus/cpp_return_pointer_from_functions.htm – BlastDV Sep 22 '14 at 19:56
  • The second time you call the function, it overwrites the first one's output unless you remember to copy it. Either provide the output matrix as another parameter, or use vectors and return one by value. – Neil Kirk Sep 22 '14 at 20:02
  • So static isn't doing anything? In my particular case, I only use that function once, so nothing should go wrong. – BlastDV Sep 22 '14 at 20:58
  • Static makes it a global variable which persists between function calls. – Neil Kirk Sep 22 '14 at 23:47
  • I see. I guess I'll have to research about what it would happen if two static variables share the same ID. Thanks. – BlastDV Sep 24 '14 at 12:36

1 Answers1

2
 for (int i=0; i<k; i++)
    output[k]= new long long int [k];

should be:

 for (int i=0; i<k; i++)
    output[i]= new long long int [k];
         //^^^^ output[k] is out of bound and you allocate space for each row
taocp
  • 23,276
  • 10
  • 49
  • 62
  • You are god d*** right! That was the answer.. It's working now. Now I only have to make sure that declaring output as static isn't going to be a problem... – BlastDV Sep 22 '14 at 19:57