Language/C
[따배씨] 14.22 함수 포인터의 사용 방법
migrationArc
2021. 7. 11. 11:07
따배씨 - 따라하며 배우는 C언어
14강 구조체_2
14.22 함수 포인터 Function Pointer 의 사용 방법
#include <stdio.h>
#include <ctype.h> // toupper(), tolower()
void ToUpper(char* str){
while(*str){
*str = toupper(*str);
str++;
}
}
void ToLower(char* str){
while (*str) {
*str = tolower(*str);
str++;
}
}
int main(){
char str[] = "Hello, World";
void (*pf)(char*);
pf = ToUpper; // Name of a function is a pointer
// pf = &ToUpper; //Acceptable
// pf = ToUpper(str); // Not acceptible in C
printf("String literal %lld\n", (long long)("Hello World!"));
// String literal 4294983546
printf("Function pointr %lld\n", (long long)ToUpper);
// Function pointr 4294983056
printf("Variable %lld\n", (long long)str);
// Variable 140732920755323
(*pf)(str);
//pf(str); //K&R X, ANSI OK
printf("ToUpper %s\n", str);
// ToUpper HELLO, WORLD
pf = ToLower;
pf(str);
printf("ToLower %s\n", str);
// ToLower hello, world
return 0;
}
void (*pf)(char*);
- 함수 포인터를 통해서 함수를 실행하기 위하여, 함수 포인터의 선언에서 parameter 와 return type 이 필요함
#include <stdio.h>
#include <ctype.h> // toupper(), tolower()
void UpdateString(char * str, int(*pf)(int)){
while(*str){
*str = (*pf)(*str);
str++;
}
}
int main(){
char str[] = "Hello, World";
UpdateString(str, toupper);
printf("ToUpper %s\n", str);
//ToUpper HELLO, WORLD
UpdateString(str, tolower);
printf("ToLower %s\n", str);
//ToLower hello, world
return 0;
}
void UpdateString(char * str, int(*pf)(int)){
while(*str){
*str = (*pf)(*str);
str++;
}
}
- 함수 포인터를 함수의 parameter 로 사용
이 글의 모든 사진과 내용의 출처는 홍정모 교수님께 있음을 알려드립니다.
http://blog.naver.com/atelierjpro
실리콘 밸리의 프로그래머 : 네이버 블로그
안녕하세요! 홍정모 블로그에 오신 것을 환영합니다. 주로 프로그래밍 관련 메모 용도로 사용합니다. 강의 수강하시는 분들은 홍정모 연구소 카페로 오세요.
blog.naver.com
http://www.inflearn.com/course/following-c
홍정모의 따라하며 배우는 C언어 - 인프런 | 강의
'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., 따라하며 배우는 C언어 '따배씨++'의 성원
www.inflearn.com