ama*_*hth 1 c struct pass-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);
}`
Run Code Online (Sandbox Code Playgroud)
代码编译但在运行时会产生分段错误(核心转储)错误
这段代码怎么了?我正在使用gcc编译器版本:gcc(Ubuntu/Linaro 4.7.3-1ubuntu1)4.7.3
请帮忙,我在等
您需要为coeff和roots结构分配内存.更换两条线
c = NULL;
r = NULL;
Run Code Online (Sandbox Code Playgroud)
通过
c = malloc ( sizeof ( struct coeff ) );
r = malloc ( sizeof ( struct roots ) );
Run Code Online (Sandbox Code Playgroud)
此外,在代码的末尾(在return
语句之前),通过释放内存
free ( c );
free ( r );
Run Code Online (Sandbox Code Playgroud)