Home > Software engineering >  "Conflicting types for 'wiperpos'" and "function returns the address of a l
"Conflicting types for 'wiperpos'" and "function returns the address of a l

Time:01-23

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

CodePudding user response:

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.

CodePudding user response:

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. e.g.

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.

  • Related