amarVashishth
amarVashishth

Reputation: 877

Passing Structures by Reference

#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

Upvotes: 1

Views: 104

Answers (2)

unxnut
unxnut

Reputation: 8839

You need to allocate memory for both coeff and roots structures. Replace the two lines

c = NULL;
r = NULL;

by

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

Also, at the end of code (before the return statement), deallocate the memory by

free ( c );
free ( r );

Upvotes: 5

jim mcnamara
jim mcnamara

Reputation: 16379

   struct coeff *c;
    struct roots *r;

These are pointers - they are not the structs themselves - they are "aimed" nowhere. Ditto for roots

Upvotes: 0

Related Questions