简体   繁体   中英

"Conflicting types for 'wiperpos'" and "function returns the address of a local variable" I've tried everything i could think of

float * GetWiperPos(float VCMD) {//user commanded voltage

    float *Wpos = malloc(2*sizeof(float));

    float Vwiper = VCMD / 10;//Voltage at potentiometer wiper output
    unsigned int Wposition = Vwiper * 205;  //wiper position in decimal (from 0-1023)

    float Wpos[2] = {(float)Wposition, Vwiper};//type casting Wposition, as it needs to be a whole number, but i assume has to be a float for the array to be happy?


    return (float *)Wpos;
}

I get function returns the address of a local variable on my return line and conflicting types on the array definition. I've tried using static rather than malloc, different ways other people have used malloc, i just don't know what else to do!

I want to return the value Float Vwiper and int Wposition when the function is called

The name Wpos is declared twice in the same scope

float *Wpos = malloc(2*sizeof(float));
//...
float Wpos[2] = {(float)Wposition, Vwiper};//type casting Wposition, as it needs to be a whole number, but i assume has to be a float for the array to be happy?

At first it is declared as a pointer

float *Wpos = malloc(2*sizeof(float));

and then as an array.

float Wpos[2] = {(float)Wposition, Vwiper};//type casting Wposition, as it needs to be a whole number, but i assume has to be a float for the array to be happy?

And you may not return a pointer to a local variable. The pointer will be invalid after exiting the function.

return (float *)Wpos;

It seems you mean something like the following

float *Wpos = malloc(2*sizeof(float));

//...

Wpos[0] = Wposition;
Wpos[1] = Vwiper;

return Wpos;

That is the declaration of the array is invalid and must be removed.

If the problem you want to solve is how to return two values from your function, pass two pointers into the function, and have it store the two return values through those. eg

void GetWiperPos(float VCMD, float *pwiper, unsigned int *pposition)
{
    *pwiper = VCMD / 10;//Voltage at potentiometer wiper output
    *pposition = *pwiper * 205;  //wiper position in decimal (from 0-1023)
}

void test_that_func(void)
{
    float wiper;
    unsigned int position;

    GetWiperPos(100, &wiper, &position);
}

Calling things like malloc() is not recommended in embedded projects.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM