例举函数指针和指针函数

函数指针: a poiterof function,本身是个指针,该指针指向一个函数,和普通指针一样,只是函数指针指可以指向一类函数。

#include<stdio.h>

 

typedef int (*COMP_METHOD)(int, int);

typedef void (*SORT)(int[], int , COMP_METHOD);

typedef struct array

{

  int value[10];

  COMP_METHOD compMethod;

  SORT sortByMethod;

}HPArray;

 

 

int compare(int a, int b)

{

  if(a > b)

  {

    return 1;

  }

  else if(a == b)

  {

    return 0;

  }

  else

  {

    return -1;

  }

}

 

void sort(int array[], int size, COMP_METHOD comp)

{

  int tmp = 0;

  int i = 0;

  int j = 0;

 

  for(i = 0; i < size - 1; i++)

  {

    for(j = i + 1; j < size; j++)

    {

      if(comp(array[i], array[j]) > 0)

      {

        tmp = array[i];

        array[i] = array[j];

        array[j] = tmp;

      }

    }

  }

}

int main(int argc,  const char* argv[])

{

  int i = 0;

  HPArray array =

  {

    .value = { -5, 9, -1, 5, 3, 7, 2, 0, 4, 8},

    .compMethod = compare,

    .sortByMethod = sort,

  };

 

  printf("before of sort:");

  for(i = 0; i < 10; i++)

  {

    printf(" %d", array.value[i]);

  }

 

  array.sortByMethod(array.value,sizeof(array.value) / sizeof(int), array.compMethod);

 

  printf("\n after of sort:");

  for(i = 0; i < 10; i++)

  {

    printf(" %d", array.value[i]);

  }

  printf("\n");

}

运行结果:

before ofsort: -5 9 -1 5 3 7 2 0 4 8

 after of sort: -5 -1 0 2 3 4 5 7 8 9

 

 

指针函数:a functionwhich return value is a pointer,本身是一个函数,只是该函数的返回值是一个指针。

 

#include<stdio.h>

 

char* strstr(const char* src, const char* substr)

{

  intn = 0;

 

  if(*substr)

  {

         while(*src != 0)

         {

                 for(n=0; *(src + n) == *(substr+n);n++)

                 {

                         if(*(substr+ n + 1) = 0)

                         {

                                 returnsrc;

                         }

                 }

                 src++;

         }

         return NULL;

  }

  else

  {

         return NULL;

  }

}

 

int main(int argc, const char* argv[])

{

  const char* hello = "hello";

  const char* sub = "hello";

  sub = strstr(hello, sub);

  if(sub == NULL)

  {

    printf("sub string no found\n");

  }

  else

  {

    printf("sub string found inlocation=%d\n",sub - hello);

  }

}

 

运行结果:

substring found in location=0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值