简体   繁体   English

包含结构本身作为参数的函数指针位于同一结构中

[英]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? 您是否认为这是在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. 我只是想知道这是否是C语言的标准属性。 Will it also compile in other compilers? 还会在其他编译器中编译吗?

It doesn't compile on gcc, clang or tinycc, and it shouldn't. 它不能在gcc,clang或tinycc上编译,因此不应该编译。 Before the typedef ends, SpriteGrid is not a thing so you can't use it. 在typedef结束之前,SpriteGrid还不算什么,所以您不能使用它。 Forward declaring the struct (with a tag) and the typedef should fix it. 转发声明该结构(带有标签),并且typedef应该对其进行修复。

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 . 依靠标签在struct tag之后立即可用的事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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