如何使用函数的typedef?

时间:2017-05-26 06:00:33

标签: c typedef

typedef bool key_equiv_fn(key x, key y);
typedef int key_hash_fn(key x);

这是什么意思? 如何定义变量,例如key_equiv_fn* equiv;

2 个答案:

答案 0 :(得分:1)

  

这是什么意思?

让我们来看看:

typedef bool key_equiv_fn(key x, key y);
          ^         ^ 
       return  name of the    ^      ^
       value   *pointer type* arguments of the functions
               of the         both of type 'key'
               function
  

如何定义key_equiv_fn* equiv

等变量
#include <stdbool.h>
typedef int key;
typedef bool key_equiv_fn(key x, key y);

// Create a function we will assign to the pointer

bool are_equal(key x, key y) { return x == y; }

int main() {
  key_equiv_fn *your_pointer;
  your_pointer = are_equal;        // assign are_equal address to the pointer
  bool equal = your_pointer(4, 2); // call the function
  return 0;
}

答案 1 :(得分:0)

您可以使用带有typedef的函数指针,如下所示,我提供了代码示例:

#include<stdio.h>
typedef struct _key/*For example*/
{
char keyy[24];
int len;
}key;

int key_equiv_fn(key x,key y) /*Function defination*/
{
 printf("Hello");
return 0;
}

typedef int (key_equiv_fn_ptrType)(key,key); /*Declare function pointer */

int main()
{
key_equiv_fn_ptrType *ptr;
ptr = key_equiv_fn;/*assign key_equiv_fn address to function pointer ptr*/
 key xx;
 key yy;
xx.len = 16;
ptr(xx,yy);/*Call function key_equiv_fn using pointer ptr*/
return 0;
}