立即学习:https://edu.csdn.net/course/play/10534/380031?utm_source=blogtoedu
学习目标
掌握指针类型之间的转换。
掌握函数指针之间的转换。
指针类型之间的转换
函数指针之间的转换
#include <stdio.h>
#include <string.h>
typedef int (*MathSum)(int[], int);
typedef int (*MathAdd)(int, int);
typedef int (*MathAgv)(int[], int);
int sum(int scores[], int len) {
int sum = 0;
int i = 0;
for (i = 0; i < len; i++) {
sum += scores[i];
}
return sum;
}
int add(int a, int b) {
return a + b;
}
int agv(int scores[], int len) {
int agv = 0;
int i = 0;
for (i = 0; i < len; i++) {
agv += scores[i];
}
return agv / len;
}
typedef struct {
MathSum sum;
MathAdd add;
MathAgv agv;
} MathTool;
void fun_point_test() {
MathTool math = { sum, add, agv };
int a[5] = { 1,2,3,4,5 };
//memset(&math, 0, sizeof(math));
printf("math.sum = %p, math.add = %p, math.agv = %p\n", math.sum, math.add, math.agv);
//math.sum = sum;
//math.add = add;
//math.agv = agv;
printf("sum(1 2 3 4 5) = %d\n", math.sum(a, sizeof(a)/sizeof(int)));
printf("add(1, 2) = %d\n", math.add(1, 2));
printf("agv(1 2 3 4 5) = %d\n", math.agv(a, sizeof(a) / sizeof(int)));
}
int main() {
char* pc = NULL;
int* pi = NULL;
int* pc2i = NULL;
char c = 'A';
int d = 10;
// 函数指针
fun_point_test();
pc = &c;
printf("sizeof(pc) = %u\n", sizeof(pc));
pi = &d;
printf("sizeof(pi) = %u\n", sizeof(pi));
// 指针类型转换
printf("*pc = %c, *pi = %d\n", *pc, *pi);
// char* -> int*, 强制类型转换
pc2i = (int*)pc;
printf("*pc2i = %c, *pc = %c\n", *pc2i, *pc);
// int* -> char*, 强制类型转换
d = 1000; // 1 byte = 255
pc = (char*)pi;
printf("*pc = %d, *pi = %d\n", *pc, *pi);
// double* -> int*
// 由大的类型转换到小的类型时,数据可能会丢失。
return 0;
}