构造函数

结构体(记录)

//C has no constructors: a function makes the struct and fills it
typedef struct {
    int x, y;
} Point;

Point pointMake(int x, int y) {
    return (Point){x, y};
}

//for a struct in the heap the function allocates it too;
//the caller frees it
Point *pointNew(int x, int y) {
    Point *p = malloc(sizeof *p);
    if (p != nullptr) {
        *p = (Point){x, y};
    }
    return p;
}

Point p1 = pointMake(1, 2);
//p1 is (1, 2)

Point *p2 = pointNew(0, 0);
if (p2 == nullptr) {
    return 1;
}
//p2 is (0, 0)

printf("p1 is (%d, %d)\n", p1.x, p1.y);
printf("p2 is (%d, %d)\n", p2->x, p2->y);
free(p2);