[习题18]C语⾔回调函数:指向...使⽤教材
函数指针语法
int (*POINTER_NAME) (int a ,int b);
⾸先,写⼀个普通的函数声明:int callme(int a, int b);
然后,⽤指针的语法格式包装函数名:int (*callme) (int a, int b)
把名字改为指针名:int (*compare_cb) (int a, int b);
此后,函数指针的变量名叫做compare_cb,可以像使⽤函数⼀样使⽤compare_cb
代码功能
命令⾏输⼊⼀组数字,进⾏冒泡排序,并输出排序结果;
排序规则 通过 指向函数的指针 传⼊决定;
ex18.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
/* Our old friend die from ex17. */
void die(const char *message)
{
if(errno) {
perror(message);
} else {
printf("ERROR: %s\n", message);
}
exit(1);
}
// a typedef creates a fake type, in this
// case for a funciton pointer
typedef int(*compare_cb)(int a, int b);
/**
* A classic bubble sort function that uses the
* compare_cb to do the sorting.
*/
int *bubble_sort(int *numbers, int count, compare_cb cmp)
switch生产流程{
int temp = 0;
int i = 0;
int j = 0;
int *target = malloc(count * sizeof(int));
if(!target)
die("Memory error.");
memcpy(target, numbers, count * sizeof(int));
for(i = 0 ; i < count; i++) {
for(j = i+1 ; j < count-1; j++) {
静态网页成品制作if(cmp(target[i], target[j+1]) > 0) {
temp = target[j+1];
target[j+1] = target[i];
target[i] = temp;
}
}
managing editor}
return target;
}
int sorted_order(int a, int b)
{
return a - b;
}
int reverse_order(int a, int b)
{
return b - a;
}
int strange_order(int a, int b)
冒泡排序代码c语言{
if(a == 0 || b == 0) {
return 0;
} else {
return a % b;
}
}
/**
颜名称高级* Used to test that we are sorting things correctly
* by doing the sort and printing it out.
*/
void test_sorting(int *numbers, int count, compare_cb cmp) {
int i = 0;
int *sorted = bubble_sort(numbers, count, cmp);
if(!sorted)
die("Failed to sort as requested.");
for(i = 0; i < count; i++) {
printf("%d ", sorted[i]);
}
printf("\n");
free(sorted);
}
int main(int argc, char *argv[])
{
if(argc < 2) die("USAGE: ex18 4 3 1 5 6");
int count = argc - 1;
int i = 0;
char **inputs = argv + 1;
int *numbers = malloc(count * sizeof(int));
if(!numbers) die("Memory error.");
for(i = 0 ; i < count; i++) {
站长之家查询numbers[i] = atoi(inputs[i]);
}
test_sorting(numbers, count, sorted_order);
test_sorting(numbers, count, reverse_order);
test_sorting(numbers, count, strange_order);
free(numbers);
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论