//函数指针 #include <stdio.h> int add(int a, int b) { return a + b; } int mul(int a, int b) { return a * b; } typedef int (*p_t)(int, int); //typedef int (*)(int, int) p_t; wrong int main(void) { int a = 8; int b = 10; p_t p; //int (*p)(int, int); //指向一类函数,参数为(int, int) 返回值为int //函数指针加小括号(*p) p = add; //指针初始化 printf("%d + %d = %d\n", a, b , p(a, b)); p = mul; printf("%d x %d = %d\n", a, b , p(a, b)); return 0; } /* akaedu@akaedu-G41MT-D3:~/lin/802$ ./1 8 + 10 = 18 8 x 10 = 80 akaedu@akaedu-G41MT-D3:~/lin/802$ */ <pre name="code" class="cpp"> //回调函数 #include <stdio.h> typedef int (*p_t)(int, int); int add(int a, int b) { return a + b; } void func(p_t p, int a, int b) { printf("%d + %d = %d\n", a, b, p(a, b)); } int main(void) { p_t p; p = add; func(p, 3, 8); return 0; }<pre name="code" class="cpp"> //变参函数 #include <stdio.h> #include <stdarg.h> void print(int last, ...) { va_list ap; // typedef char * va_list char *p; va_start(ap, last); //找出第一个指针的地址保存到ap指针里面 // ap = &last + sizeof(last) p = va_arg(ap, char *); // 取出当前指针的内容 //va_arg(ap, type); // *((type)(ap += sizeof(type) - sizeof(type))) while(p != NULL){ printf("%s", p); p = va_arg(ap, char *); } printf("\n"); va_end(ap); //类似于malloc的free //#define ap NULL } int main(void) { print(100, "hehe", "haha", "xixi", NULL); print(10, "hehe", "hello", "akak", NULL); print(1, "hehe", NULL); return 0; }
</pre><pre code_snippet_id="441585" snippet_file_name="blog_20140803_4_1439010" name="code" class="cpp">
</pre><pre code_snippet_id="441585" snippet_file_name="blog_20140803_5_2862542" name="code" class="cpp"><pre name="code" class="cpp">#include <stdio.h> #include <stdarg.h> void print_int(int num, ...) { int i; // n = num; va_list ap; va_start(ap, num); // p = va_arg(ap, num); while(num > 0){ i = va_arg(ap, int); printf("%d ", i); num--; } va_end(ap); } int main(void) { print_int(5, 1, 2, 3, 4, 5); putchar('\n'); print_int(8, 88, 2, 3, 4, 5, 88, 66, 8 ); putchar('\n'); return 0; } /* akaedu@akaedu-G41MT-D3:~/lin/802$ ./6 1 2 3 4 5 88 2 3 4 5 88 66 8 */<pre name="code" class="cpp"> //my_printf #include <stdio.h> #include <stdarg.h> void myprintf(const char *format, ...) { va_list ap; char c; va_start(ap, format); while((c = *format++)){ switch(c){ case 'c':{ char ch = va_arg(ap, int); // char ch = va_arg(ap, char); putchar(ch); break; } case 's':{ char *p = va_arg(ap, char *); fputs(p, stdout); break; } case 'd':{ int p = va_arg(ap, int); int i = p + '0'; putchar(i); break; } // case 'p':{ // } default: putchar(c); } } va_end(ap); } int main(void) { myprintf("c\ts\td\n", 'm', "hello", 8); return 0; } /* akaedu@akaedu-G41MT-D3:~/lin/802$ ./8 m hello 8 akaedu@akaedu-G41MT-D3:~/lin/802$ */