0

I have declared 2 structs: point (which holds 2 doubles) and circle (which holds a point and the radius of the circle, a double).

typedef struct {
    double x;
    double y;   
} point;

typedef struct {
    point m;
    double r;
} circle;

To create a circle I use these 2 functions:

point* read_point() {
    point* p = malloc (sizeof(point));
    printf("\nx middle:");
    scanf("%lf",&p->x);
    printf("\ny middle:");
    scanf("%lf",&p->y);
    return p;
}

circle* read_circle() {
    circle* c = malloc(sizeof(circle));
    point* p = read_point();
    printf("\nradius circle:");
    scanf("%lf",&c->r);
    c->m = *p;
}

In my main I declare an array of circle pointers, add one circle and then try to print out the center point and the radius. (At this point my program crashes.)

circle* array[3];
array[0] = read_circle();
print_circle(array[0]); //Crashes

This is what the print function looks like:

void print_circle(circle* c){
    point p = c->m;
    printf("\n%lf",p.x);
    printf("\n%lf",p.y);
    printf("\n%lf",c->r);
}
MC93
  • 791
  • 6
  • 14
Agnaroc
  • 45
  • 4

2 Answers2

4

read_circle isn't returning c (or anything, for that matter).

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • 2
    Thank you, this was indeed the problem. 2 hours of work for a simple exercise from school and I miss something like that. – Agnaroc Aug 12 '15 at 15:43
0

You might also want to check the return value of malloc().

Mikrosaft
  • 195
  • 1
  • 8
  • If I cast using (point*) and (circle*) respectively, is my solution then correct ? (I know I have to free after I use point and circle) – Agnaroc Aug 12 '15 at 15:49
  • 1
    @Agnaroc [Don't cast the return value of malloc()](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) What I ment is to check if malloc() failed (i.e. returned NULL) – Mikrosaft Aug 12 '15 at 16:03
  • @Mikrosaft: Good advice, but wouldn't solve the current problem. – Scott Hunter Aug 12 '15 at 16:20
  • @ScottHunter True, but since you already answered it, I didn't feel like I needed to write it again. (It would have made more sense if I commented on his question, but I still can't due to low reputation) – Mikrosaft Aug 12 '15 at 16:34
  • @Mikrosaft in the school examples malloc is always casted. Why shouldn't it be done here ? – Agnaroc Aug 12 '15 at 16:49
  • @Agnaroc Read the link I sent, it gives a few reasons why not to cast. The only reason I can think of to cast malloc(), is to add compilability between C and C++ (in C++ the cast is mandatory), but since you're writing in C, and since in C++ [you shouldn't use malloc()](http://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new), I see no reason to cast. – Mikrosaft Aug 12 '15 at 17:08