[good]c语言函数指针的运用

发布时间 2023-11-29 09:59:44作者: 风中狂笑
#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);
}