0

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

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'
4

2 回答 2

3

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

new_hash(15, print_test, comp_func);

或者(并且等效地),使用该&符号来明确发生了什么:

new_hash(15, &print_test, &comp_func);
于 2012-05-01T01:03:00.597 回答
2

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

编辑:您也可能误解了函数指针的概念。你不应该传递print_test(word)to的结果new_hash- 你应该传递print_test自己。(另外,更改其返回类型)

于 2012-05-01T01:04:10.203 回答