Consider I have a matrix A n*n
elements defined as pointer of pointer **A
. I want to pass a submatrix (B nb*nb
) of A to another function as a pointer, perform some mathematical operation on the submatrix and return it back to the original function. The submatrix, returned from the function, is also member of the matrix A in the same location as before. What is the best way to send it?
You cannot do this using only pointer arithmetic. What you have is an array of arrays. Assuming outer array holds rows and inner arrays hold the elements (columns) of each row, you can pass a pointer to the middle of the outer array to skip rows but you cannot skip columns. If you need to skip columns as well you have two options:
Pass the original matrix along with offsets and the submatrix size. This means the fuction needs to be coded in a way to be able to handle submatrices.
Create a new outer array to hold pointers to the element of each inner array that corresponds to the column required. E.g. (assuming elem
is the type of each element in the matrix:
elem **get_submatrix(elem **mat, int n, int x, int y, int m)
{
elem **submat = (elem **)calloc(m, sizeof(elem*));
int i;
for(i = 0; i < m; i++)
{
submat[i] = mat[y++] + x;
}
return submat;
}
Of course you later have to free
the submatrix (only the outer array, not the inner arrays)