Search code examples
cpointersmatrixmultiplication

How to calculate determinant of a matrix using pointers in c?


I am writing a program to calculate determinant of a matrix using pointers with size up to 3x3 and I've started with writing the formula for 2x2 matrix.

I got an error and it displayed "expression must have arithmetic type" in places of the parentheses at the beginnings of multiplied expressions.

It seems that the program recognize the values as pointers instead of just multiplying values, but I'm not sure either. How do I fix it?

void determinant(int size, int matrix[][MAXSIZE])
{
    int d;
    if(size == 2)
    {
        d = matrix * ((matrix + 1) + 1) - ((matrix + 1) + 0) * ((matrix + 0) + 1);
        printf("Determinant of your matrix: %d\n", d);
    }
}

Solution

  • Why not just matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]?

    You should probably pass a more type-safe argument than int matrix[][] to the function, though (e.g. create some kind of a struct MATRIX_2_2).

    For the sake of exercise, if you really want to use pointer arithmetics, you'd probably want to write something like:

    d = (**matrix) * (*(*(matrix + 1) + 1)) - (*(*(matrix + 0) + 1)) * (*(*(matrix + 1) + 0));
    

    Here, every first de-reference (that's what an asterisk is) gets a 1-D array of the matrix, and the second one gets a specific value.