首页 > 代码库 > 函数数组

函数数组

#include <unistd.h>typedef int (FUN) (void);typedef FUN_PTR (FUN*) ;int print1(void){    printf("1111111\n");    sleep(1);}int print2(void){    printf("2222222\n");    sleep(1);}int print3(void){    printf("333333\n");    sleep(1);}int print4(void){    printf("444444\n");    sleep(1);}int print5(void){    printf("555555\n");    sleep(1);}FUN* functable[]={    print1 ,    print2,    print3,    print4,    0};int main(){    FUN **fnc_ptr  ;     int i ;        for(fnc_ptr = functable ; *fnc_ptr ; ++fnc_ptr){        (*fnc_ptr)();    }    fnc_ptr = functable;    for(i=0 ; i<5;i++){        (*(fnc_ptr+i))();    }    fnc_ptr = functable;    for(i=0 ; i<5;i++){//Segmentation fault         (fnc_ptr[i])();    }}/*1111111222222233333344444411111112222222333333444444Segmentation fault*/

 

改:int main(){    FUN **fnc_ptr  ;     int i ;        for(fnc_ptr = functable ; *fnc_ptr ; ++fnc_ptr){        (*fnc_ptr)();    }    #if 1    fnc_ptr = functable;    for(i=0 ; i< 4;i++){        (*(fnc_ptr+i))();    }    #endif        #if 1     fnc_ptr = functable;    for(i=0 ; i< 4;i++){         (fnc_ptr[i])();    }    #endif}/*111111122222223333334444441111111222222233333344444411111112222222333333444444*/

 

函数数组