[英]Function pointer confusion
我正在嘗試在c中使用函數指針和Abstract數據類型。 這是我第一次使用它,我真的很困惑。 無論如何,當我嘗試編譯這段代碼時,我給了我一個錯誤。 我第一次運行它起作用。 但是當我通過開關a
和b
改變參數時。 它給了我舊的答案,從未更新。
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.