函数指针: 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