Reputation: 21
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;
}
Upvotes: 1
Views: 405
Reputation: 311038
Instead of these lines
double *arr[]=(double *)malloc(2*sizeof(double));
arr[2]={{x1}, {x2}};
return arr;
you need to write within the function pq
double *arr = malloc( 2 * sizeof( double ) );
if ( arr != NULL )
{
arr[0] = x1;
arr[1] = x2;
}
return arr;
And in main
double *arr = NULL;
double a = 0.0, b = 0.0;
scanf("%lf %lf", &a, &b );
^^^^^^
if ((a*a)-(b*a)>=0)
{
arr = pq( a, b );
}
else
{
printf("Es gibt keine reellen L\224sungen.");
}
if ( arr != NULL )
{
for (int i=0; i<2;i++)
{
printf( "%f", arr[i] );
^^^
}
}
free( arr );
Upvotes: 1
Reputation: 51845
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;
}
Upvotes: 0
Reputation: 117906
The problem is with this line
arr[2]={{x1}, {x2}};
arr[2] =
is assigning to the 3rd element of the array, which is out of bounds. And you cannot use that brace syntax to assign to an array slice like that. Instead
arr[0] = x1;
arr[1] = x2;
Upvotes: 0