#include <stdio.h>
#include <stdlib.h>
int (*(*ptr[2])[2])(); //arr of pointers to the array of func pointer
int (*arr_1[2])(int ,int);//arr of function pointers
(*arr_1[])()={add1, sub1};//add1 ,sub1 are simple functions returning int
int (*arr_2[2])(int ,int);
int a,b, user_func_choice;
(*arr_2[])()={add2, sub2};
int lib_choice,user_lib_choice;
int main(int argc , char* argv[]) {
printf("enter the lib number\t 1:Lib1 , 2:Lib2 \n");
scanf("%d", &user_lib_choice);
lib_choice=user_lib_choice-1;
if(lib_choice==0){
printf("Welcome to lib1\n");
printf("enter func choice==> 1: Add , 2: subtract\n");
scanf("%d", &user_func_choice);
printf("enter the numbers.\n");
scanf("%d%d",&a,&b);
int func_choice= user_func_choice-1;
ptr[0]= arr_1;
if(func_choice==0)
{
int sum1=(*(*ptr[lib_choice])[func_choice])(a,b);
printf("sum1=%1d\n\n", sum1);
}
else if(func_choice==1)
{
int subtract1=(*(*ptr[lib_choice])[func_choice])(a,b);
printf("sub1=%1d\n\n", subtract1);
}
else{printf("InValid Function/operator choice\n");}
return;
}
if(lib_choice=1){
int a, b, user_func_choice;
printf("welcome to lib2\n");
printf("enter func choice: 1: Add , 2: subtract\n");
scanf("%d", &user_func_choice);
printf("enter the numbers.\n");
scanf("%d%d",&a,&b);
ptr[1] = arr_2;
int func_choice= user_func_choice-1;
if(func_choice==0)
{
int sum2=(*(*ptr[lib_choice])[func_choice])(a,b);
printf("sum2=%1d\n\n", sum2);
}
else if(func_choice==1)
{
int subtract2=(*(*ptr[lib_choice])[func_choice])(a,b);
printf("sub2=%1d\n\n", subtract2);
}
return;
}
else{printf("InValid library choice\n");
}
return 0;
}
每一件事工作正常這裏 但我想要的是硬編碼庫的初始化(LIB1或LIB2)讓用戶而不是初始化函數指針數組指定他想要初始化的庫的數量。這樣如何分配/只當我調用一個函數來進行
int main(int argc , char* argv[]){
printf("enter the lib number\t 1:Lib1 , 2:Lib2 \n");
scanf("%d", &user_lib_choice);
if(argc!=2){printf("please specify the library number as sencond argument\n");return 0;}
int lib_choice_cmd=atoi(argv[1]);
if(lib_choice==1)
{
lib1_init();
}
else if(lib_choice==2)
{
lib1_init();
lib2_init();
}
lib_init()的東西是會做初始化process.If用戶指定的lib NUM爲1,我將僅初始化lib1內的功能。我這樣做是爲了LIB1,但是這給了我一個錯誤
lib1_init(){
(*arr_1[2])(int ,int)={add1 , sub1};
}
當我做
lib1_init(){
arr_1[0]=add1;
arr_1[1]=sub1;
}
這給了我分割fault.Pleae告訴我什麼是錯
有一個在初始化「絕對沒有的增值,只有當我調用本功能離子」。初始化是在編譯/加載時完成的,因此沒有運行時性能的後果。 ...除非你想分配_different_函數。 –