函数指针混乱

时间:2012-05-01 00:58:12

标签: c pointers structure function-pointers abstract-data-type

我正在尝试在c中使用函数指针和抽象数据类型。这是我第一次使用它,我真的很困惑。无论如何,当我尝试编译此代码时,我给了我一个错误。我第一次运行它。但是当我通过开关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'

2 个答案:

答案 0 :(得分:3)

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

new_hash(15, print_test, comp_func);

或者(等效地),使用&符号清楚地说明发生了什么:

new_hash(15, &print_test, &comp_func);

答案 1 :(得分:2)

您应该在使用之前声明函数。如果不这样做,编译器会假定它返回int,并在您尝试取消引用时给出错误(因为它取消引用int是不可能的)。

编辑: 你也可能误解了函数指针的概念。你不应该将print_test(word)的结果传递给new_hash - 你应该通过print_test本身。 (另外,改变其返回类型)