Search code examples
cdynamic-memory-allocationdynamic-arraysreturn-typefunction-definition

returning dynamically created array from function


I'm trying to return the solutions of the pq-formula as a dynamically created array. What's the correct way to do that? This is my function:

double *pq (double a, double b)
{
 double x1=(-1)*(a/2)-sqrt((a/2)*(a/2)-b);
 double x2=(-1)*(a/2)+sqrt((a/2)*(a/2)-b);
 double *arr[]=(double *)malloc(2*sizeof(double));
 arr[2]={{x1}, {x2}};

 return arr;

}

Also, why do I get an 'expected an expression' error on arr[2]={{x1}, {x2}}; ?

My main function:

    int main ()
{
    double *arr[2]={0}, a=0.00, b=0.00;

    scanf("%lf %lf", a,b);

    if ((a*a)-(b*a)>=0)
    {
        for (int i=0; i<2; i++)
        {
            arr[i] = pq(a,b);
        }   
    }

    else
    {
        printf("Es gibt keine reellen L\224sungen.");
    }
 
    for (int i=0; i<2;i++)
    {
        printf("%lf", arr[i]);
    }


    return 0;
}

Solution

  • You can't initialize such a dynamically allocated array en bloc. Instead, assign values to each element, in turn. With a little reordering of your function, you can even remove the need for your intermediate (x1 and x2) variables:

    double *pq (double a, double b)
    {
        double *arr = malloc(2*sizeof(double)); // No need to cast!
        arr[0] = (-1)*(a/2)-sqrt((a/2)*(a/2)-b);
        arr[1] = (-1)*(a/2)+sqrt((a/2)*(a/2)-b);
        return arr;
    }
    

    On the casting of the return value of the malloc function, see: Do I cast the result of malloc?

    Also, you have to change the way your main function works; don't declare a local array and try to assign data after the call; just use the 'array' returned from your function, as the elements' values will already be there:

    int main ()
    {
        double a=0.00, b=0.00;
    
        scanf("%lf %lf", &a, &b); // Note the address (&) operators!
    
        if ((a*a)-(b*a)>=0)
        {
            double *arr = pq(a, b);
            for (int i=0; i<2; i++)
            {
                printf("%lf", arr[i]);
            }
            free(arr); // Don't forget to free the memory!
        }
        else
        {
            printf("Es gibt keine reellen L\224sungen.");
        }
        return 0;
    }