找出n个数组中相同的元素
1 int arrays_common(int arrs[][10], int cnt, int* res, int len_res ) 2 { 3 int* index_arr = (int*)calloc(cnt, sizeof(int)); //cnt是第一维 数组的编号 4 int common_cnt = 0 ; //result中数组的下标 5 int max_index ; 6 int min_val ; 7 int min_index ; 8 int index ; 9 while(1) 10 { 11 for(index = 0 ; index < cnt - 1; index ++) 12 { 13 if( arrs[index][index_arr[index]] != arrs[index + 1][index_arr[index + 1]] ) 14 { 15 break ; 16 } 17 } 18 if(index < cnt - 1) 19 { 20 min_index = 0 ; 21 min_val = arrs[0][index_arr[0]] ; 22 for(index = 1; index < cnt; index ++) 23 { 24 if(arrs[index][index_arr[index]] < min_val) 25 { 26 min_index = index ; 27 min_val = arrs[index][index_arr[index]] ; 28 } 29 } 30 index_arr[min_index] ++ ; 31 }else 32 { 33 res[common_cnt] = arrs[0][index_arr[0]] ; 34 common_cnt ++ ; 35 for(index = 0 ; index < cnt; index ++) 36 { 37 index_arr[index] ++ ; 38 } 39 } 40 for(max_index = 0, index = 1; index < cnt; index ++) 41 { 42 if(index_arr[index] > index_arr[max_index]) 43 { 44 max_index = index ; 45 } 46 } 47 if(index_arr[max_index] >= 10) 48 { 49 return common_cnt; 50 } 51 } 52 }
函数指针
函数名实际上代表函数的地址。函数指针是指向函数的指针变量。 因而“函数指针”本身首先应是指针变量,只不过该指针变量指向函数。这正如用指针变量可指向整型变量、字符型、数组一样,这里是指向函数。如前所述,C在编译时,每一个函数都有一个入口地址,该入口地址就是函数指针所指向的地址。有了指向函数的指针变量后,可用该指针变量调用函数,就如同用指针变量可引用其他类型变量一样,在这些概念上是大体一致的。函数指针有两个用途:调用函数和做函数的参数。
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 5 int mycmp(int left,int right); 6 int mycat(int left,int right); 7 int mycpy(int left,int right); 8 void func_1(); 9 void func_2(); 10 void func_3(); 11 12 int process(int a,int b,int (*pf)(int a,int b)); 13 14 int main(int argc,char* argv) 15 { 16 /* 17 int a = 3; 18 int b = 4; 19 int res; 20 res = process(a,b,&mycmp); 21 printf("res: %d\n",res); 22 res = process(a,b,&mycat); 23 printf("res: %d\n",res); 24 res = process(a,b,&mycpy); 25 printf("res: %d\n",res); 26 */ 27 int ch; 28 void (*p[4])() = {NULL,&func_1,&func_2,&func_3}; 29 while(ch = getchar()) 30 { 31 if(ch=='\n') 32 continue; 33 //system("cls"); 34 (*p[ch - '0'])(); 35 } 36 return 0; 37 } 38 39 int mycmp(int left,int right) 40 { 41 return left+right; 42 } 43 int mycat(int left,int right) 44 { 45 return left-right; 46 } 47 int mycpy(int left,int right) 48 { 49 return left*right; 50 } 51 52 int process(int a,int b,int (*pf)(int a,int b)) 53 { 54 return (*pf)(a,b); 55 } 56 57 void func_1() 58 { 59 putchar('h'); 60 putchar('\n'); 61 } 62 void func_2() 63 { 64 putchar('y'); 65 putchar('\n'); 66 } 67 void func_3() 68 { 69 exit(1); 70 }