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

标签 c struct function-pointers

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;

你认为这是在 struct 中使用函数指针的有效方式吗?
注意:请不要说自己试试看。编译没有问题。我只想知道这是否是 C 语言的标准属性。它也会在其他编译器中编译吗?

最佳答案

它不能在 gcc、clang 或 tinycc 上编译,也不应该。 在 typedef 结束之前,SpriteGrid 不是一个东西,所以你不能使用它。转发声明结构(带有标记),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;

或者,你可以这样做

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;

依赖于标签在 struct tag 之后立即可用的事实。

关于c - 包含结构本身作为参数的函数指针位于同一结构内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51294855/

相关文章:

c - C 是否将结构填充初始化为零?

c++ - STL 函数式——为什么?

c make文件编译错误

c - 在 C 中打印长度超过 80 个字符的行

c - 在 C 中使用 EOF 和 getchar() 进行字符计数

使用 execve 调用 ls 和其他

c - 在 CUDA 中使用常量内存和结构数组

c - 在C中实现2个具有相同类型和名称但参数不同的函数

c++ - 传递函数到动态链接库

C:什么是函数指针转换?