Reputation: 25
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);
}
}
Upvotes: 2
Views: 1677
Reputation: 1
The question of computing the determinant is a basic math question (totally unrelated to C) and most linear algebra courses would explain how to do that. You actually need to understand how you would compute that "by hand".
A different question is how to represent matrixes (as an abstract data type) in a C program. I would suggest using flexible array members (and pointers to struct
-s containing them), and I detailed more how to do that in this answer (which of course you need to complete for your needs).
By combining both approaches (the math side and the programming side) you can complete your homework.
Don't forget to enable all warnings and debug info when compiling (e.g. compile using gcc -Wall -Wextra -g
with GCC; see also the advice given here), and read How to debug small programs.
Upvotes: 1
Reputation: 773
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.
Upvotes: 2