[英]Error in dynamically allocating memory in C
I am trying to calculate the determinant of an NxN matrix. 我正在尝试计算NxN矩阵的行列式。 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 *"
错误:无法将类型为“ int”的值分配给类型为“ float *”的实体
error: a value of type "int" cannot be assigned to an entity of type "float **"
错误:无法将类型为“ int”的值分配给类型为“ 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. 您需要添加
#include <stdlib.h>
以便正确声明malloc()
。
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 *
. 就目前而言,编译器非常宽松(C89模式),并且允许隐式函数声明,因此,当编译器遇到
malloc()
,它将假定它是一个返回int
的函数,而不是正确的void *
。
You need to change your compilation options until the compiler complains more loudly. 您需要更改编译选项,直到编译器发出更大的抱怨为止。 For example, if you use GCC, you should consider:
例如,如果您使用GCC,则应考虑:
gcc -std=c99 -Wall -Wextra -Wstrict-prototypes -Wmissing-prototypes ...
You may prefer, or even need, to use -std=gnu99
instead -std=c99
; 您可能更喜欢甚至需要使用
-std=gnu99
而不是-std=c99
; that enables many extensions while still using the C99 core language. 可以在仍使用C99核心语言的情况下启用许多扩展。 But using options along those lines and ensuring there are no compilation warnings is good discipline.
但是,按照这些原则使用选项并确保没有编译警告是很好的纪律。 Using
-Werror
enforces the discipline; 使用
-Werror
加强训练; it converts any warning message from the compiler into an error, so the compilation fails. 它将来自编译器的所有警告消息转换为错误,因此编译失败。
您需要包括头文件stdlib.h
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.