I am trying to calculate the determinant of an NxN matrix. This piece of code gives an error in lines where I try to allocate the memory dynamically.
error: a value of type "int" cannot be assigned to an entity of type "float *"
error: a value of type "int" cannot be assigned to an entity of type "float **"
double CalcDeterminant( float **mat, int order)
{
float **minor;
unsigned short i;
float det = 0;
// order must be >= 0
// stop the recursion when matrix is a single element
if( order == 1 )
return mat[0][0];
// the determinant value
// allocate the cofactor matrix
**minor = malloc((order-1) * sizeof(float *));
for(i=0;i<order-1;i++)
minor[i] = malloc((order-1) * sizeof(float));**
//float *mat2d = malloc( rows * cols * sizeof( float ));
for(i = 0; i < order; i++ )
{
// get minor of element (0,i)
GetMinor( mat, minor, 0, i , order);
// the recusion is here!
det += (i%2==1?-1.0:1.0) * mat[0][i] * CalcDeterminant(minor,order-1);
//det += pow( -1.0, i ) * mat[0][i] * CalcDeterminant( minor,order-1 );
}
// release memory
for(i=0;i<order-1;i++)
free(minor[i]);
free(minor);
return det;
}
You need to add the line #include <stdlib.h>
so that malloc()
is properly declared.
As it stands, the compiler is being very lax (C89 mode) and allowing implicit function declarations, so when the compiler comes across malloc()
, it assumes that it is a function that returns an int
, instead of the correct void *
.
You need to change your compilation options until the compiler complains more loudly. For example, if you use GCC, you should consider:
gcc -std=c99 -Wall -Wextra -Wstrict-prototypes -Wmissing-prototypes ...
You may prefer, or even need, to use -std=gnu99
instead -std=c99
; that enables many extensions while still using the C99 core language. But using options along those lines and ensuring there are no compilation warnings is good discipline. Using -Werror
enforces the discipline; it converts any warning message from the compiler into an error, so the compilation fails.
您需要包括头文件stdlib.h
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.