So here's my code, with already implemented check for input data.
However, it doesn't reject float and eg. 3table as input for the size of a matrix.
How to fix that?
Code:
#include <stdlib.h>
#include <stdio.h>
float determinant (float * data, int num);
int error = 0;
int main ()
{
int num, i;
char temp[BUFSIZ];
float *data;
float *counter;
float value;
char *p; /*used in function strtol in order to find the end of the input number*/
printf("Enter the size of matrix: ");
do
{
scanf("%s", temp);
num = strtol(temp, &p, 10);
if (num > 10 || num < 1)
{
printf("matrix size must be integer from interval 1-10\n");
}
}while(num > 10 || num < 1 || !(*p == '\n' || *p == '\0'));
printf ("Size of the matrix %d by %d\n", num, num);
if (1)
{
data = malloc(sizeof(*data) * (num * num));
if (data != NULL)
{
for (counter = data, i = 0; counter < data + (num * num); counter++, i++) {
printf("Enter the %d element: ", (i + 1));
scanf("%s", temp);
*counter = atof(temp);
}
value = determinant (data, num);
free (data);
if (!error)
printf("Value = %f\n", value);
}
else
printf("Memory allocation failed!\n\n");
}
else
printf("Invalid size of matrix\n");
return 0;
}
float determinant (float * data, int num) {
float result = 0;
int i, j, place;
float value = 1;
float * counter, * new_data, * new_counter;
if (num > 1) {
for (place = 1; place < num + 1; place++) {
new_data = malloc(sizeof(*new_data) * (num - 1) * (num - 1));
if (new_data != NULL) {
for (counter = data, i = 1, j = 1, new_counter = new_data; counter < data + (num * num); counter++, i++) {
if (i % (num + 1) == 0) {
j++;
i = 1;
}
if (i == place || j == 1)
continue;
*new_counter = *counter;
new_counter++;
}
value = (*(data + (place - 1))) * determinant(new_data, num - 1);
if (error) {
free(new_data);
return 0;
}
if (place % 2 == 0)
value *= -1;
result += value;
free(new_data);
}
else {
printf("\nMemory allocation failed!\n");
error = 1;
return 0;
}
}
return result;
}
return *data;
}