Function that returns more than one variable in c

Asked

Viewed 28 times

1

I need to do a function that takes 3 floats and returns the average, the largest number among the 3 and the difference between the average and the largest. I tried to make the return by a pointer but one of the variables is not returned correctly and I can not find explanations on google, nor alternative ways to solve my problem. I know there must be other ways to do this program, but in the statement I have some restrictions: I cannot use global variables, including struct, the function parameters should be only 3 floats. What I wanted to know is what’s wrong in this program, why isn’t it working? Whether it’s about using the pointer or the logic is flawed...

//a comparação de valores não está correta
//o valor de mmd[1] não está sendo retornada corretamente

float *func_mmd(float a, float b, float c)//func_media_maior_diferenca
{
    float mmd[3];

    mmd[0]=(a+b+c)/3;//media

    mmd[1]=a;
    if(a>b || a>c)//comparação maior numero
    {
        mmd[1]=a;
    }
    else
        if(b>c || b>a)
        {
            mmd[1]=b;
        }
        else
            if(a==b && a==c && b==c)
            {
                mmd[1]=a;
            }
            else
            {mmd[1]=c;}


    mmd[2]=mmd[0]-mmd[1];//diferença

    printf("%f",mmd[1]);//este printf é só pra eu saber o que está sendo armazenada na variavel que calcula  o maior numero
    return (mmd);
}

int main()
{
    float a,b,c,*mmd;

    scanf("%f",&a);
    scanf("%f",&b);
    scanf("%f",&c);

    mmd=func_mmd(a,b,c);
    printf("\nA media eh:%f",mmd[0]);
    printf("\nO maior valor eh: %f",mmd[1]);
    printf("\nA diferenca entre a media e o maior numero eh: %f",mmd[2]);

    return 0;
}
  • The problem is that you are returning the pointer of an automatic variable (float mmd[3]) that ceases to exist as soon as the function func_mmd() returns. A simple solution is to declare mmd in the main() function and pass it as a float mmd[] parameter, so it is guaranteed that the mmd memory area will exist throughout the execution of the program.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.