设计思路
- 定义结构体:定义一个包含函数指针成员的结构体,该函数指针指向计算两个数之和的函数。
- 动态分配结构体数组:使用
malloc
或C++
中的new
来动态分配结构体数组内存。
- 初始化函数指针:为每个结构体元素的函数指针成员赋值,指向计算两个数之和的函数。
- 调用函数指针并输出结果:遍历结构体数组,调用每个元素的函数指针,计算并输出结果。
- 内存释放:使用
free
(C
语言)或delete[]
(C++
)释放动态分配的内存,避免内存泄漏。
实现代码(C语言示例)
#include <stdio.h>
#include <stdlib.h>
// 定义计算两个数之和的函数
int add(int a, int b) {
return a + b;
}
// 定义结构体
typedef struct {
int (*func)(int, int); // 函数指针
} Calculator;
int main() {
int n = 3; // 假设分配3个结构体元素
Calculator *calculators = (Calculator *)malloc(n * sizeof(Calculator));
if (calculators == NULL) {
perror("malloc");
return 1;
}
// 为每个结构体元素的函数指针赋值
for (int i = 0; i < n; i++) {
calculators[i].func = add;
}
// 调用函数指针并输出结果
for (int i = 0; i < n; i++) {
int result = calculators[i].func(2, 3); // 假设计算2 + 3
printf("Result of calculation %d: %d\n", i + 1, result);
}
// 释放内存
free(calculators);
return 0;
}
实现代码(C++示例)
#include <iostream>
// 定义计算两个数之和的函数
int add(int a, int b) {
return a + b;
}
// 定义结构体
struct Calculator {
int (*func)(int, int); // 函数指针
};
int main() {
int n = 3; // 假设分配3个结构体元素
Calculator *calculators = new Calculator[n];
// 为每个结构体元素的函数指针赋值
for (int i = 0; i < n; i++) {
calculators[i].func = add;
}
// 调用函数指针并输出结果
for (int i = 0; i < n; i++) {
int result = calculators[i].func(2, 3); // 假设计算2 + 3
std::cout << "Result of calculation " << i + 1 << ": " << result << std::endl;
}
// 释放内存
delete[] calculators;
return 0;
}
动态内存分配与释放
- C语言:使用
malloc
分配内存,如果分配失败,malloc
返回NULL
,需要进行错误处理。使用free
释放内存,并且只释放一次,避免多次释放导致未定义行为。
- C++:使用
new
分配内存,如果分配失败,会抛出std::bad_alloc
异常。使用delete[]
释放动态分配的数组内存,确保配对使用new[]
和delete[]
,以正确调用对象的析构函数(如果有)并释放内存,防止内存泄漏。