简体   繁体   中英

Can anyone please explain me this code?

C code to demonstrate the use of function pointers.

#include<stdio.h>
struct geoobject
{
        enum{CIR=0,REC,TRG}gcode;
        union
        {
                struct cir{double x,y,r;}c;
                struct rec{double x,y,w,h;}r;
                struct trg{double x,y,b,h;}t;
        };
};
typedef void(*DrawFunc)(struct geoobject);

Typedefed function pointer.

void drawcir(struct geoobject go)
{
        printf("Circle:(%lf,%lf,%lf)\n",go.c.x,go.c.y,go.c.r);
}
void drawrec(struct geoobject go)
{
        printf("Rec:(%lf,%lf,%lf,%lf)\n",go.r.x,go.r.y,go.r.w,go.r.h);
}
void drawtrg(struct geoobject go)
{
        printf("Triangle:(%lf,%lf,%lf,%lf)\n",go.t.x,go.t.y,go.t.b,go.t.h);
}
DrawFunc DrawArr[]={drawcir,drawrec,drawtrg};
int main(void)
{
        struct geoobject go;
        go.gcode=CIR;
        go.c.x=2.3;go.c.y=3.6;go.c.r=1.2;
        DrawArr[go.gcode](go);
        go.gcode=REC;
        go.r.x=4.5;go.r.y=1.9;go.r.w=4.2;go.r.h=3.8;
        DrawArr[go.gcode](go);
        go.gcode=TRG;
        go.t.x=3.1;go.t.y=2.8;go.t.b=4.4;go.t.h=2.7;
        DrawArr[go.gcode](go);
        return 0;
}

Confused with typedef void(*DrawFunc)(struct geoobject) and its usage in the program.Please explain.

typedef void(*DrawFunc)(struct geoobject) means that Drawfunc is now a typdef (or name/alias) of a pointer to a function which is taking a struct geoobject as argument, and returning void.

In the program, an array of function pointers is declared :

DrawFunc DrawArr[]={drawcir,drawrec,drawtrg};

All three functions drawcir(), drawrec() and drawtrg() respect the definition of the typedef DrawFunc and can be aliased as such.

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