『返回指針的函數』和『指向函數的指針』非常相似,使用時特別注意區分。
返回指針的函數定義:char * upper(char *str)
指向函數的指針:char (*fun)(int int)
返回指針的函數:
char * upper(char *str) { char *dest = str; while(*str != NULL) { if(*str >= 'a' && *str <= 'z') { *str -= 'a' - 'A'; } str++; } return dest; }
指向函數的指針:
int add(int a,int b) { return a+b; } int min() { int (*fun)() = add; int result = (*fun)(1,2); char hello[] = "Hello"; char *dest = upper(heLLo); }
int result = (*fun)(1,2); 是指向 add 函數的函數,執行結果 result=3。
char *dest = upper(heLLo); 將 hello 字符串中的小寫字母全部轉換為大寫字母。
參考自:https://www.runoob.com/cplusplus/cpp-return-arrays-from-function.html