函数指针,数组指针,指针数组,指向函数指针数组的指针,函数指针数组
6题
(*(char**(*)(char**,char**))0)(char**,char**)
把0强制转换为函数地址指向某个函数,并解引用进行使用,改变函数地址,操作内存,减少内存浪费
函数指针,回调函数
数组元素排序,结构体排序
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
/*
int main()
{
int arr[10] = { 0 };
int(*p)[10] = &arr;//取出数组的地址
int(*pf)(int, int);//函数指针
int(*pfArr[4])(int, int);//pfArr是一个数组-函数指针的数组
//ppfArr是一个指向函数指数组的指针
int(*(*ppfArr)[4])(int, int) = &pfArr;
//ppfArr 是一个数组指针,指针指向的数组有4个元素
//指向的数组的每个元素的类型是一个函数指针int(*)(int,int)
return 0;
}
*/
/*
//回调函数
void print(char* str)
{
printf("hehe:%s", str);
}
void test(void(*p)(char*))
{
printf("test\n");
p("bit");
}
int main()
{
test(print);
return 0;
}
*/
struct Stu
{
char name[20];
int age;
};
int cmp_int(const void* e1, const void* e2)
{
//比较两个整型值
return *(int*)e1 - *(int*)e2;
}
void cmp_stu_by_age(const void* e1, const void* e2)
{
//比较结构体
return (((struct Stu*)e1)->age - ((struct Stu*)e2)->age);
}
void cmp_stu_by_name(const void* e1, const void* e2)
{
//比较名字就是比较字符串
//字符串不能用<>=来比较,应该使用strcmp函数
return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);
}
void Swap(char* buf1, char* buf2, int width)
{
int i = 0;
for (i = 0; i < width; i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
void bubble_sort(void* base, int sz, int width, int (*cmp)(void* e1, void* e2))
{
int i = 0;
for (i = 0; i < sz - 1; i++)
{
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (cmp((char*)base + j * width, (char*)base + (j + 1) * width) > 0)
{
Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
}
}
}
}
void test4()
{
int arr[10] = { 10,9,8,7,6,5,4,3,2,1 };
int sz = sizeof(arr) / sizeof(arr[0]);
//使用bubble_sort的程序员一定知道自己排的是什么数据
//就应该知道如何比较待排序的数据中的元素
bubble_sort(arr, sz, sizeof(arr[0]), cmp_int);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
}
void test5()
{
struct Stu s[3] = { {"zhangsan",20},{"lisi",30} ,{"wangwu",10} };
int sz = sizeof(s) / sizeof(s[0]);
//bubble_sort(s, sz, sizeof(s[0]), cmp_stu_by_age);
bubble_sort(s, sz, sizeof(s[0]), cmp_stu_by_name);
int i = 0;
int w = sizeof(s[0]);
struct Stu *p;
for (i = 0; i < 3; i++)
{
p = &s[i];
//printf("%s %d ", s[i].name, s[i].age);//结构体打印三种方法
//printf("%s %d ", (*p).name, (*p).age);
printf("%s %d ", p->name, p->age);
}
}
int main()
{
//test4();
test5();
return 0;
}