0

I am trying to write a C program using GSL to find the roots of a cubic equation following the instructions here: http://www.gnu.org/software/gsl/manual/html_node/Cubic-Equations.html. This is what I came up with:

#include <stdio.h>
#include <gsl/gsl_poly.h>

double *x0,*x1,*x2;
int roots;

int
main (void)
{
    roots = gsl_poly_solve_cubic(0,0,0,x0,x1,x2);

    printf( " %d ", roots);

    return 0;
}

The arguments are 0,0,0 because I wanted to test if it works first. The code compiles but when run, it crashes with no output.

What am I doing wrong?

Legendre
  • 3,108
  • 7
  • 31
  • 46

3 Answers3

2

x0, x1 and x2 are just dangling pointers - change the code to:

double x0,x1,x2;
int roots;

int
main (void)
{
    roots = gsl_poly_solve_cubic(0,0,0,&x0,&x1,&x2);

    printf( " %d ", roots);

    return 0;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
2

You're misunderstanding how reference semantics are implemented in C. Please read this answer I just wrote on the exact same topic.

Solution:

double x0, x1, x2;

int roots = gsl_poly_solve_cubic(0, 0, 0, &x0, &x1, &x2);

Nutshell: The caller must take the address-of the recipient variable. The recipient variable must exist.

Community
  • 1
  • 1
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
1

According to you lonk we have gsl_poly_solve_cubic (double a, double b, double c, double * x0, double * x1, double * x2). You declare 3 double pointers without allocating any memory ... this will result in a segfault.
Try to declare double variables and just pass their address :

#include <stdio.h>
#include <gsl/gsl_poly.h>


double x0,x1,x2;
int roots;

int
main (void)
{
    roots = gsl_poly_solve_cubic(0,0,0,&x0,&x1,&x2);

    printf( " %d ", roots);

    return 0;
}
Kwariz
  • 1,306
  • 8
  • 11