I need to get float value from parameter
float aCoefficiants[50]=
{
-0.000890288188976378,
..
}
float bCoefficiants[50] =
{
89.1324281858268,
..
}
float* cArray ;
Get_Coefficient_From_Value(2211,(float*)&cArray);
printf(">> out %f %f",cArray[0],cArray[1]);
And function:
void Get_Coefficient_From_Value(int32_t pulse, float * coefficient)
{
coefficient[0] = aCoefficiants[0];
coefficient[1] = bCoefficiants[0];
printf(">> in %f %f\n",(coefficient[0]),(coefficient[1]));
}
in parameter that I expected: >> in -0.000890 89.132431
But out values does not match with original >> out-0.001010 99.323250
How get float variables in parameter corrrectlu and solve this problem?
EDIT:
https://onlinegdb.com/Jy_ylNlVf
CodePudding user response:
float* cArray;
That is an uninitialised pointer and dereferencing it results in Undefined Behaviour. Change that to an actual array. The following complete program should work.
#include <stdio.h>
#include <stdint.h>
void Get_Coefficient_From_Value(int32_t pulse, float * coefficient)
{
coefficient[0] = -0.000890288188976378;
coefficient[1] = 89.1324281858268;
printf(">> in %f %f\n",(coefficient[0]),(coefficient[1]));
}
int main(void)
{
float cArray[2];
Get_Coefficient_From_Value(2211, cArray);
printf(">> out %f %f",cArray[0],cArray[1]);
return 0;
}
CodePudding user response:
This is undefined behavior:
float* cArray ;
Get_Coefficient_From_Value(2211,(float*)&cArray);
cArray
is not pointing to anything valid. Further, you are casting the pointer to cArray to a float pointer and passing that in. (Technically, the pointer to an array is the array, but I digress).
Hence, when that function writes into cArray[0] and cArray[1], you are stomping on memory that doesn't belong to you.
Better:
float cArray[2] = {0};
Get_Coefficient_From_Value(2211,cArray);
When you invoke it that way, the cArray array will "degrade to a pointer" when passed in as a parameter. The two coEfficient assignments in that function will moving values into valid memory.