admin 管理员组

文章数量: 1087649


2024年5月21日发(作者:强制结束运行快捷键)

c语言实现结构体 函数指针

在 C 语言中,可以使用结构体(Struct)和函数指针来实现一些高级功能。下面是一

个示例,展示了如何使用结构体和函数指针来实现一个简单的计算器:

```c

#include

// 定义一个结构体来表示计算器的操作

struct CalculatorOperation {

char operator;

void (*function)(int, int);

};

// 定义一些计算器的操作函数

void add(int a, int b) {

printf("a + b = %dn", a + b);

}

void subtract(int a, int b) {

printf("a - b = %dn", a - b);

}

void multiply(int a, int b) {

printf("a * b = %dn", a * b);

}

void divide(int a, int b) {

if (b != 0) {

printf("a / b = %dn", a / b);

} else {

printf("Error: 不能除以 0n");

}

}

int main() {

// 创建一个结构体数组,存储不同的操作

struct CalculatorOperation operations[] = {

{'+', add},

'-', subtract},

'*', multiply},

'/', divide}

};

// 输入两个数和操作符

int num1, num2, choice;

printf("请输入第一个数: ");

scanf("%d", &num1);

printf("请输入第二个数: ");

scanf("%d", &num2);

printf("请选择操作符 (+, -, *, /): ");

scanf("%c", &choice);

// 查找对应的操作函数并调用

struct CalculatorOperation *operation = NULL;

for (int i = 0; i < sizeof(operations) / sizeof(operations[0]); i++) {

if (operations[i].operator == choice) {

operation = &operations[i];

break;

}

}

if (operation != NULL) {

operation->function(num1, num2);

} else {

printf("Error: 无效的操作符n");

}

return 0;

}

```

在上述示例中,首先定义了一个`CalculatorOperation`结构体,其中包含操作符和对

应的函数指针。然后,定义了四个用于执行加、减、乘、除操作的函数。

在`main`函数中,创建了一个`CalculatorOperation`结构体数组,存储了不同的操作。

然后,输入两个数和操作符,通过遍历结构体数组找到对应的操作函数,并调用该函数执行

计算。

这样的实现方式使得代码更加灵活和可扩展,可以方便地添加或修改不同的操作。希望

这段代码能够帮助到你,如果你还有其他疑问,请随时向我提问。


本文标签: 结构 操作 函数 实现 定义