在C结构中的函数指针 [英] Function Pointers within structures in C

查看:133
本文介绍了在C结构中的函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

typedef struct Item{

  int i;
  int j;    
  void (*fooprint)(item*);

}item;

void fooprint(item *it){
  printf("%d\n",it.i);
}


int main(){

  item myitem;
  myitem.i=10;
  myitem.j=20;
  myitem.fooprint = fooprint;

  myitem.fooprint(&myitem);
  return 0;
}

这code给出在一个无效错误(足迹)(项目的)。 该错误是前'*'令牌预期')'。我缺少的东西吗?当我做同样不使用指针结构工程。例子:void(*足迹)(项目)

This code gives a error at void (footprint)(item). "The error is expected ‘)’ before ‘*’ token ". Am I missing something ? When I do the same without using pointer to the structure is works. Example : void (*footprint)(item)

推荐答案

类型项目还没有当您使用它闻名。你可以解决一个向前声明。

The type item is not known yet when you use it. You can solve that with a forward declaration.

typedef struct Item item;
struct Item {
    int i;
    int j;
    void (*fooprint)(item*);
};

另一种可能性是不使用的typedef 来定义成员:

typedef struct Item {
    int i;
    int j;
    void (*fooprint)(struct Item *);
} item;

这篇关于在C结构中的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆