简体   繁体   中英

function pointer containing the struct itself as parameter being inside the same struct

typedef struct
{
    int x1,y1,x2,y2;
    int (*division_mode_x)(int i,int x1,int x2,SpriteGrid grid);
    int (*division_mode_y)(int i,int y1,int y2);
}SpriteGrid;

Do you think this is a valid way to use function pointers inside struct?
Note : Please don't say try and see it for yourself. There is no problem with compilation. I just wanna know if this is a standard property of the C language. Will it also compile in other compilers?

It doesn't compile on gcc, clang or tinycc, and it shouldn't. Before the typedef ends, SpriteGrid is not a thing so you can't use it. Forward declaring the struct (with a tag) and the typedef should fix it.

typedef struct SpriteGrid SpriteGrid; 
typedef struct SpriteGrid /*this typedef is redundant now*/
{
    int x1,y1,x2,y2;
    int (*division_mode_x)(int i,int x1,int x2,SpriteGrid grid);
    int (*division_mode_y)(int i,int y1,int y2);
}SpriteGrid;

Alternatively, you can do

typedef struct SpriteGrid
{
    int x1,y1,x2,y2;
    //without the forward typedef `SpriteGrid` isn't usable
    //here yet, but `struct SpriteGrid` is 
    int (*division_mode_x)(int i,int x1,int x2,struct SpriteGrid grid);
    int (*division_mode_y)(int i,int y1,int y2);
}SpriteGrid;

relying on the fact that a tag becomes usable immediately after struct tag .

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