简体   繁体   中英

Dereferencing an array of struct pointers

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);
}

read_circle不会返回c (或其他原因)。

您可能还需要检查malloc()的返回值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM