繁体   English   中英

函数指针混乱

[英]Function pointer confusion

我正在尝试在c中使用函数指针和Abstract数据类型。 这是我第一次使用它,我真的很困惑。 无论如何,当我尝试编译这段代码时,我给了我一个错误。 我第一次运行它起作用。 但是当我通过开关ab改变参数时。 它给了我旧的答案,从未更新。

typedef struct data_{
  void *data;
  struct data_ *next;
}data;

typedef struct buckets_{
  void *key;
}buckets;

typedef struct hash_table_ {
  /* structure definition goes here */
  int (*hash_func)(char *);
  int (*comp_func)(void*, void*);
  buckets **buckets_array;
} hash_table, *Phash_table;

main(){

  Phash_table table_p;
  char word[20]= "Hellooooo";
  int a;
  a = 5;
  int b;
  b = 10;
  /*Line 11*/
  table_p = new_hash(15, *print_test(word), *comp_func(&a, &b)); 

}

int *print_test(char *word){
  printf("%s", word);
}

int *comp_func(int *i,int *j){

  if(*i < *j){
    printf("yeeeeeeee");
  }else{
    printf("yeaaaaaaaaaaaaa");
  }
}

Phash_table new_hash(int size, int (*hash_func)(char *), int (*cmp_func)(void *, void *)){
  int i;
  Phash_table table_p;
  buckets *buckets_p;
  hash_table hash_table;

  table_p = (void *)malloc(sizeof(hash_table));

  /*Setting function pointers*/
  table_p -> hash_func = hash_func;
  table_p -> comp_func = cmp_func;

  /*Create buckets array and set to null*/
  table_p -> buckets_array = (buckets **)malloc(sizeof(buckets_p)*(size+1));

  for(i = 0; i < size; i++){
    table_p -> buckets_array[i] = NULL;
  }

  return table_p;
}

这是错误消息:

functions.c: In function 'main':
functions.c:11:26: error: invalid type argument of unary '*' (have 'int')
functions.c:11:45: error: invalid type argument of unary '*' (have 'int')
Helloyeaaaaaaaaaaaaa

新错误:

functions.c:11:3: warning: passing argument 2 of 'new_hash' makes pointer from integer without a cast [enabled by default]
hash.h:29:13: note: expected 'int (*)(char *)' but argument is of type 'int'
functions.c:11:3: warning: passing argument 3 of 'new_hash' makes pointer from integer without a cast [enabled by default]
hash.h:29:13: note: expected 'int (*)(void *, void *)' but argument is of type 'int'

如果要将函数作为函数指针传递,只需提供名称:

new_hash(15, print_test, comp_func);

或替代地(等效地),使用&符号清楚地说明正在发生的事情:

new_hash(15, &print_test, &comp_func);

您应该在使用函数之前声明它。 如果不执行此操作,则编译器会假定它返回int ,并且在尝试取消引用它时会给您一个错误(因为取消引用int是不可能的)。

编辑:您可能还会误解了函数指针的概念。 您不应该将print_test(word)的结果传递给new_hash您应该传递print_test本身。 (此外,更改其返回类型)

暂无
暂无

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

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