1
#include <stdio.h>
#include <math.h>


struct coeff
{
    int a;
    int b;
    int c;
};


struct roots
{
    double r1;
    double r2;
};


void calculateRoots(struct coeff*, struct roots*);


int main(int argc, char const *argv[])
{
    struct coeff *c;
    struct roots *r;
    c = NULL;
    r = NULL;

    c->a = 10;
    c->b = 20;
    c->c = 30;

    calculateRoots(c,r);

    printf("The roots are : %lf & %lf\n", r->r1, r->r2);

    return 0;
}


void calculateRoots(struct coeff *cef, struct roots *rts)
{
    rts->r1 = (-(cef->b) + sqrt((cef->b)*(cef->b) - 4*(cef->a)*(cef->c)) ) / 2*(cef->a);
    rts->r2 = (-(cef->b) - sqrt((cef->b)*(cef->b) - 4*(cef->a)*(cef->c)) ) / 2*(cef->a);
}`

Code compiles but on running gives a Segmentation Fault (core dumped) error

Whats wrong in this code ?? I'm using a gcc compiler version : gcc (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3

Please help, I'm waiting live

4

2 回答 2

5

您需要为 coeff 和 root 结构分配内存。替换两行

c = NULL;
r = NULL;

经过

c = malloc ( sizeof ( struct coeff ) );
r = malloc ( sizeof ( struct roots ) );

此外,在代码末尾(return语句之前),通过以下方式释放内存

free ( c );
free ( r );
于 2013-06-07T17:57:41.803 回答
0
   struct coeff *c;
    struct roots *r;

这些是指针——它们本身不是结构——它们无处“瞄准”。同上根

于 2013-06-07T17:58:00.083 回答