c语言中函数指针用法

复制代码
#include <stdio.h>
#define MAX 10

void swap(int *x, int *y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

void fun(int *height, int *age)
{
    int n = 10;
    *height = n * 10;
    *age = n * 2000;
}

int *createArray(int size)
{
    int i;
    int *arr = (int *)(malloc(sizeof(int) * size));
    for (i = 0; i < size; i++)
    {
        arr[i] = i * i;
    }
    return arr;
}

int *sumArray(int arr)
{
    return 0;
}

int add(int x, int y)
{
    return x + y;
}

int substract(int x, int y)
{
    return x - y;
}

int multiply(int x, int y)
{
    return x * y;
}

int divide(int x, int y)
{
    return x / y;
}

int module(int x, int y)
{
    return x % y;
}

typedef int (*operation_fun)(int, int);

void main()
{
    int num = 0;
    int (*ptr_add)(int, int) = add;
    void (*ptr_swap)(int, int) = swap;

    int a = 100, b = 200;
    int sum = ptr_add(a, b);
    printf("the result is %d\n", sum);
    ptr_swap(&a, &b);
    printf("before swap a is %d, b is %d\n", a, b);
    swap(&a, &b);
    printf("after swap a is %d, b is %d\n", a, b);

    operation_fun operations[] = {
        &add,
        &substract,
        &multiply,
        &divide,
        &module};

    // int (*operations[])(int, int) = {add, substract, multiply, divide, module};
    // int (*operations[])(int, int) = {&add, &substract, &multiply, &divide, &module};

    char *arr[] = {"add", "substract", "multiply", "divide", "module"};

    int result = 0;
    int i, j;
    for (i = 0; i < 5; i++)
    {
        result = operations[i](10, 20);
        printf("%s of two number result is %d\n", arr[i], result);
    }

    int p_height;
    int p_age;
    fun(&p_height, &p_age);
    printf("height is %d and age is %d\n", p_height, p_age);

    int c = 30;
    int *ptr1 = &c;
    int **ptr2 = &ptr1;

    printf("c is %d\n", c);
    printf("ptr1 is %d\n", *ptr1);
    printf("ptr2 is %d\n", **ptr2);
}
复制代码

 

posted on   风中狂笑  阅读(6)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示