代码示例
#include <stdio.h>
// 定义不同类型参数和返回值的函数
int func1(int a) {
return a + 1;
}
double func2(double b) {
return b * 2;
}
// 定义函数指针类型
typedef int (*Func1Ptr)(int);
typedef double (*Func2Ptr)(double);
// 定义函数指针数组
union FunctionPointers {
Func1Ptr func1Ptr;
Func2Ptr func2Ptr;
};
int main() {
// 初始化函数指针数组
union FunctionPointers functionPointers[2];
functionPointers[0].func1Ptr = func1;
functionPointers[1].func2Ptr = func2;
// 使用函数指针数组
int result1 = functionPointers[0].func1Ptr(5);
double result2 = functionPointers[1].func2Ptr(3.5);
printf("Result 1: %d\n", result1);
printf("Result 2: %lf\n", result2);
return 0;
}
解释
- 定义不同函数:首先定义了两个不同类型参数和返回值的函数
func1
和 func2
。
- 定义函数指针类型:使用
typedef
为不同函数类型定义了函数指针类型 Func1Ptr
和 Func2Ptr
,这样做可以使代码更易读和维护。
- 使用联合定义函数指针数组:考虑到不同平台下内存对齐因素,使用
union
来定义函数指针数组 FunctionPointers
。union
所有成员共享相同的内存位置,这样可以避免因不同函数指针类型大小不一致导致的内存对齐问题。在不同平台下,无论指针大小如何变化(32位平台指针通常4字节,64位平台指针通常8字节),union
都能适应。
- 初始化和使用函数指针数组:在
main
函数中,初始化函数指针数组,然后通过数组元素调用相应的函数。这样就实现了在不同平台下正确定义和使用函数指针数组,确保程序的平台兼容性。