有没有办法将结构类型传递给ac函数

Luu*_*sen 3 c

我有一些代码具有多个彼此非常相似的功能,可以根据结构中一个字段的内容查找列表中的项目.这些函数之间的唯一区别是查找结构的类型.如果我可以传入类型,我可以删除所有代码重复.

我也注意到在这些函数中也发生了一些互斥锁定,所以我想我可能会把它们留下来......

tia*_*mex 7

如果确保将字段放置在每个此类结构中的相同位置,则可以简单地转换指针以获取字段.该技术用于许多低级系统库,例如BSD套接字.

struct person {
  int index;
};

struct clown {
  int index;
  char *hat;
};

/* we're not going to define a firetruck here */
struct firetruck;


struct fireman {
  int index;
  struct firetruck *truck;
};

int getindexof(struct person *who)
{
  return who->index;
}

int main(int argc, char *argv[])
{
  struct fireman sam;
  /* somehow sam gets initialised */
  sam.index = 5;

  int index = getindexof((struct person *) &sam);
  printf("Sam's index is %d\n", index);

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这样做会失去类型安全性,但这是一种有价值的技术.

[我现在已经测试了上面的代码并修复了各种小错误.有了编译器,这会容易得多.]