# Thread: Problem-pointer reference-Kth power of matrix

1. ## Problem-pointer reference-Kth power of matrix

The below problem is to find the kth power of a matrix.

Code:
```#include<iostream>
using namespace std;
int main()
{
double **a;
int r,k;
double **matrixExpon(double**,int);

cout<<"the no of rows in the matrix is"<<endl;
cin>>r;

a=new double*[r];

for(int i=0;i<r;i++)
{
a[i]=new double(r);
}
cout<<"Value of k is "<<endl;
cin>>k;
for(int i=1;i<k;i++)
a=matrixExpon(**a,r);

}

double **matrixExpon(double **a,int r)
{
double **b;
b=new double *[r];
int i;
for(i=0;i<r;i++)
{
b[i]=new double [r];
}

int j,k,sum=0;
for(i=0;i<=r;i++)
{
for(j=0;j<=r;j++)
{
for(k=0;k<=r;k++)
sum=sum+a[i][k]*a[k][j];

b[i][j]=sum;
sum=0;
}
}
return b;
}```

Compilation Error :

cannot convert ‘double’ to ‘double**’ for argument ‘1’ to ‘double** matrixExpon(double**, int)’|

2. In main(), remove the asterixes from the line "a=matrixExpon(**a,r);" . That will get the code to compile. **a is of type double. It is being passed to a function expecting to receive a pointer to a pointer to double. Hence the compilation error.

However, even if it is modified to compile, that code does not compute the k'th power of a matrix. And it gives a massive memory leak, due to repeatedly losing track of dynamically allocated memory. That is result of poor logic in how you have gone about things. You need to think through your problem much more carefully.

3. Originally Posted by grumpy
In main(), remove the asterixes from the line "a=matrixExpon(**a,r);" . That will get the code to compile. **a is of type double. It is being passed to a function expecting to receive a pointer to a pointer to double. Hence the compilation error.

However, even if it is modified to compile, that code does not compute the k'th power of a matrix. And it gives a massive memory leak, due to repeatedly losing track of dynamically allocated memory. That is result of poor logic in how you have gone about things. You need to think through your problem much more carefully.

More complex memory management (30 points)
Using a for loop, write an exponentiation function to compute the k-th
power of a matrix A = (a1,1 , . . . , al,l ) :
double **matrixExpon(double **a, int r)

i was told to solve this problem.. using that function.. by a reputed college ..

i have no alternative..

4. You miss my point.

It is both your implementation of that function, and then the manner that your code is calling that function, that are flawed.

5. okay... i will change it..