2017-10-12 5 views
1

오늘 약 function pointer(binary tree)에 대한 숙제를 받았습니다. 내가 이해할 수없는 코드의 덩어리가있다 ... 나는 function pointer이 무엇인지 이해하고 작동 방법하지만 function pointers 2에 대해구조체 함수 포인터에 대한 함수 포인터

header.h가 (1 parameter에)

typedef struct _node_ { 
int key; 
struct _node_ *left; 
struct _node_ *right; 
} node; 

typedef struct _bstree_ { 
node *root_node; 
int (*compare_keys)(int x, int y); //this code 
} bstree; 
X 코드 here` y와 동일하게 처리하거나, 하나 될 입력할지

C 파일

void bst_init_with_comp_operator(bstree *bst, int(*comp)(int x, int y)) { 
bst_init(bst); 

bst->compare_keys = comp; // what does this mean? a fucntion pointer parameter to function pointer to struct? 

} 

// 샘플 콘텐츠를 반환 -1, X가 Y보다로서 취급 할 필요가있는 경우 예상되는, 0, X가되어야 하는지를 y보다 큰 것으로 취급됩니다. ...

일반적으로 우리가이

int function(int x, int y) 
{ return x+y;} 

int (*pointerf) (int , int) 

pointerf = function; 

pointerf(2,3) 
같은 뭔가가 필요

int compare (int x , int y) 
{ 
if(x < y) return -1; 
else if(x == y) return 0; 
else return 1; 

} 

main.c를

bstree tree; 
bst_init_with_comp_operator(&tree,compare(2,3)) 

하지만 작품을 나던 :

그래서이 기능을 생성
+0

"does not work"를 정의하십시오. 그것은 컴파일 또는하지 않습니까? 실행됩니까? 그것은 추락합니까? 하드 드라이브가 지워졌습니까? –

+0

그것은 나 에게이 오류를 제공합니다 : 경고 : bst_init_with_comp_operator의 인수 2 전달 캐스트없이 interger에서 포인터를 만듭니다 – Newuser1234567

+1

그 결과는 "비교 (2,3)"그냥 "비교"될 것이 아니라 결과를 전달하기 때문입니다. – PaulR

답변

0

방금 bst_init_with_comp_operator(&tree,compare))이 필요하고, 이것은 함수 주소를 매개 변수로 전달하며, compare(a,b) 일 경우이 함수의 결과를 전달하므로 정수 1, 0 또는 -1을 전달합니다.

관련 문제