Anirudh Murali
Anirudh Murali

Reputation: 633

Matrix multiplication using pointers

I was learning to implement dimensional arrays with the help of Pointers, stumbled upon a program - Multiplication of Matrices, but with pointers. I've understood the Matrix multiplication program without using pointers. It comes like this:

for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
    mult[i][j]+=a[i][k]*b[k][j];

Using Pointers, the code is like this:

for(i=0;i<r1;i++)    
for(j=0;j<c2;j++)    
for(k=0;k<c1;k++)    
    *(*(c+i)+j)+=*(*(a+i)+j)*(*(*(b+k)+j));

I don't get the above piece of code, what exactly are they Dereferencing and which asterisk represents Multiplication?

Sorry for my ignorance, Thanks in advance (:

Upvotes: 0

Views: 2411

Answers (1)

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31153

All these matrices are two level arrays and consist of an array of pointers to arrays of values. This makes it a bit ugly to do it in the latter way.

First you need to find the pointer to the array you want. That's the first derefence *(c+i). Then you add to this the item you want from that array and dereference again, so it becomes *(*(c+i)+j). That's all it takes.

Now the only actual multiplication is the asterisk between the closing and opening braces:

 *(*(c+i)+j)+=*(*(a+i)+j)  *  (*(*(b+k)+j));
                           ^ this

If that code looks ugly to you, I can tell you something that will help: you can use the first type code with pointers too. c[i] is exactly the same as *(c+i). So just use

c[i][j] += a[i][j] * b[k][j];

and your life will be at least 7.935% better, guaranteed.

Upvotes: 2

Related Questions