Search code examples
cpointersstructurefunction-pointersabstract-data-type

Function pointer confusion


I'm trying to use function pointers and Abstract data types in c. This is my first time using it and I'm really confused. Anyways when I tried to compile this code I gave me an error. The first time I ran it worked. But when I change the arguments by switch a and b. It gave me the old answer and never updated.

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;
}

This is the error message:

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

New error:

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'

Solution

  • If you want to pass a function as a function-pointer, simply provide the name:

    new_hash(15, print_test, comp_func);
    

    or alternatively (and equivalently), use the & symbol to make it clear what's going on:

    new_hash(15, &print_test, &comp_func);