(C/C++) 指向函數的指標

最近再跟指標作朋友, 正好遇到函數與指標. 其實函數也在程式內也是有屬於本身的位址ios

因此指標一樣能指向函數, 在此釐清本身的觀念以及記錄下來.spa

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 const double * f1 (const double ar[], int n);
 8 const double * f2 (const double *, int n);
 9 const double * f3 (const double *, int);
10 
11 int main(int argv, char * argc[]){
12         double av[3] = { 1112.3, 1542.6, 2227.9};
13 
14         const double *(*pv)(const double *, int n) = f1;
15         cout << (*pv)(av,3) << " : " << *(*pv)(av,3) << endl;
16 
17         auto p2 = f2;
18         cout << p2(av, 3) << " : " << *p2(av, 3) << endl;
19 
20         const double *(*p3[3]) (const double *, int) = {f1, f2, f3};
21         auto pb = p3;
22 
23         for(int i = 0; i < 3; i++){
24                 cout << pb[i](av,3) << " : " << *pb[i](av, 3) << endl;                
25         }
26         return 0;
27 }
28 
29 
30 const double * f1 (const double ar[], int n){
31     return ar;
32 }
33 
34 const double * f2 (const double ar[], int n){
35     return ar + 1;
36 }
37 
38 const double * f3 (const double ar[], int n){
39     return ar + 2;
40 }

首先宣告 3個 會回傳  const double * 的函數, 而 f1, f2, f3 分別回傳 input ar不一样的位址code

在main裡頭我也利用3種不一样的方法去指向函數, 第一次遇見只覺得有點複雜. 可是看穿了就是用 (*pv) 去取代 function 名稱blog

const double * (*pv) (const double *, int n);

若是须要宣告成陣列則能够使用下列宣告方式input

const double * (*p3[3]) (const double *, int);

目前经常使用且理解使用指標的使用時機:io

若是你沒有须要 array 的 size, 直接利用 pointer to array 單純宣告一個 *ptr便可function

int * ptr = array;
char matrixA[10][10];
char (*ptr)[10];
ptr = matrixA; 

 雙重指標以及指標, 3如下行取值, 取位址, class

如果要取得 a 的位址 : &a, ptr, * ptrstream

a 的數值 : a, *ptr, **pgc

ptr 的位址 : &ptr, p, &*p

p 的位址 : &p

int a = 30;
int *ptr =  &a;
int **p = &ptr;