* Computer Science/C

5. 함수 포인터

soicem 2017. 12. 8. 19:44

 반환형과 매개변수를 명시하여 그에 해당하는 함수를 받을 수 있는 포인터 변수다.  c는 늘 그렇듯이 문법만 맞춰주면 돌아간다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
 
void (*say)(char *string= NULL;
void (*end)(void= NULL;
 
void say_1(char *str){
    printf("%s \n", str);
}
 
void say_2(char *str){
    printf("%s Hello world!\n", str);
}
 
void say_3(void){
    printf("\n");
}
 
main(){
    say = say_1;
    say("best in the world");
    say=say_2;
    say("soicem");
    end = say_3;
    end();
}
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
 
int (*getMax)(int l[], int length) = NULL;
 
int getMaxInArray(int l[], int length){
    int max = 0;
    int i;
 
    for(i = 0; i< length; i++){
        if(l[i] > max)
            max = l[i];
    }
    return max;
}
 
int main(){
    int l[4= {1,2,5,3};
    getMax = getMaxInArray;
    printf("%d\n", getMaxInArray(l, 4));
    printf("%d\n", getMax(l, 4));
    
    return 0;
}
 
cs


'* Computer Science > C' 카테고리의 다른 글

6. stack, queue  (0) 2017.12.10
1. gcd, quickSort, swap  (0) 2017.12.06