Skip to content

函数指针

C
  1 #include <stdio.h>                                                                    
  2 
  3 int add(int a, int b)
  4 {
  5     return a + b;
  6 }
  7 
  8 int main(void){
  9     int sum;
 10     int (*fp)(int, int);
 11     fp = add;
 12     sum = fp(1, 2);
 13     printf("sum = %d\n", sum);
 14     return 0;
 15 }
 16 
     
     
 result:

		sum = 3
  • int func(void); ===> 定义函数

  • int (*fp)(void); ===> 定义函数指针

  • fp = func ===> 指针赋值

  • (*fp)() ===> 调用函数

  • fp() ===>调用函数简化

void指针

特点:1.可以指向任何数据类型,赋值给其他类型的时候需要强制转换类型

​ 2.任意类型转为void*类型再转回来数据不发生改变

​ 3.一般不参加指针运算, 也不可以用*访问

C
  1 #include <stdio.h>                                                                   
  2 #include <stdlib.h>
  3 #include <string.h>
  4 
  5 void date_copy(void *dst, const void *src, size_t len)
  6 {
  7     char *d = dst;
  8     const char *s = src;
  9     for(size_t i = 0; i<len ;i++)
 10     {
 11         *d++ = *s++;
 12     }
 13 }
 14 int main(void){
 15     char a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
 16     char *buf = (char *)malloc(10);
 17     memset(buf, 0, 10);
 18     date_copy(buf, a, 10);
 19     for(int j=0 ; j<10 ; j++)
 20         printf("%d ", buf[j]);
 21     puts("");
 22     return 0;
 23 }