Why am I getting a segmentation fault? C programming -
here's code i'm getting seg fault at. i'm pretty sure has pass-by-reference, confuses me , i'm not sure if i'm doing right.
#include <math.h> #include <stdio.h> #include <stdlib.h> #include "utils.h" #define pi 3.1415926535897932384626433832795 int circlestatistics(double radius, double *diameter, double *circumference, double *area){ *diameter = radius * 2; *circumference = pi * radius * 2; *area = pi * radius * radius; if (radius <= 0 || diameter == null || circumference == null || area == null) printf("an error has occured\n"); homecoming 1; }else{ homecoming 0; } }
now here code i'm using phone call function , test it.
#include "utils.h" #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv){ // tests circlestatistics double radius = 3; double *diameter = null, *circumference = null, *area = null; circlestatistics(radius, diameter, circumference, area); printf("expected output: radius = 3, diameter = 6, circumference ~= 18.849555, area ~= 28.2743339\n"); printf("actual output: radius = %.0f, diameter = %.0f, circumference ~= %.7f, area ~= %.7f\n", radius, *diameter, *circumference, *area); }
you dereferencing pointer arguments , after checking, whether not null... seek this:
#include <math.h> #include <stdio.h> #include <stdlib.h> #include "utils.h" #define pi 3.1415926535897932384626433832795 int circlestatistics(double radius, double *diameter, double *circumference, double *area){ if (radius <= 0 || diameter == null || circumference == null || area == null) printf("an error has occured\n"); homecoming 1; }else{ /* know, neither of arguments point null... */ *diameter = radius * 2; *circumference = pi * radius * 2; *area = pi * radius * radius; homecoming 0; } }
c fault
No comments:
Post a Comment