FX-指针函数与函数指针

1.指针函数(返回指针的函数)

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

// 指针函数:返回一个指向整型的指针
int* createArray(int size) {
    int *arr = (int *)malloc(size * sizeof(int)); // 动态分配内存
    if (arr == NULL) {
        printf("内存分配失败\n");
        exit(1);
    }
    for (int i = 0; i < size; i++) {
        arr[i] = i + 1; // 初始化数组
    }
    return arr; // 返回指针
}

int main() {
    int *arr = createArray(5); // 调用指针函数
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]); // 输出数组内容
    }
    free(arr); // 释放内存
    return 0;
}

2. 函数指针(指向函数的指针)

cpp 复制代码
#include <stdio.h>

// 定义一个函数
int add(int a, int b) {
    return a + b;
}

int main() {
    // 定义函数指针
    int (*funcPtr)(int, int);

    // 将函数地址赋值给函数指针
    funcPtr = add;

    // 通过函数指针调用函数
    int result = funcPtr(3, 5);
    printf("3 + 5 = %d\n", result);

    return 0;
}

3. 函数指针的高级用法

3.1函数指针作为参数(回调函数)

cpp 复制代码
#include <stdio.h>

// 回调函数类型
typedef int (*Operation)(int, int);

// 定义一个函数,接受函数指针作为参数
int calculate(int a, int b, Operation op) {
    return op(a, b);
}

// 具体操作函数
int add(int a, int b) {
    return a + b;
}

int subtract(int a, int b) {
    return a - b;
}

int main() {
    int result1 = calculate(10, 5, add);      // 传递 add 函数
    int result2 = calculate(10, 5, subtract); // 传递 subtract 函数

    printf("10 + 5 = %d\n", result1);
    printf("10 - 5 = %d\n", result2);

    return 0;
}

3.2函数指针数组

cpp 复制代码
#include <stdio.h>

// 定义几个函数
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }

int main() {
    // 定义函数指针数组
    int (*funcArray[3])(int, int) = {add, subtract, multiply};

    // 通过函数指针数组调用函数
    printf("10 + 5 = %d\n", funcArray[0](10, 5));
    printf("10 - 5 = %d\n", funcArray[1](10, 5));
    printf("10 * 5 = %d\n", funcArray[2](10, 5));

    return 0;
}

4. 函数指针与指针函数的区别

特性 指针函数 函数指针
定义 返回值是指针的函数 指向函数的指针变量
语法 int* func(int a, int b); int (*funcPtr)(int, int);
用途 返回动态分配的内存或数组 实现回调、函数表等
调用方式 直接调用 通过指针调用

5. 总结

  • 指针函数:返回值是指针的函数,通常用于返回动态分配的内存或数组。

  • 函数指针:指向函数的指针,用于实现回调、函数表等高级功能。

相关推荐
康谋自动驾驶38 分钟前
康谋分享 | 自动驾驶仿真进入“标准时代”:aiSim全面对接ASAM OpenX
人工智能·科技·算法·机器学习·自动驾驶·汽车
C++ 老炮儿的技术栈1 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法
yychen_java2 小时前
R-tree详解
java·算法·r-tree
MarkHard1232 小时前
Leetcode (力扣)做题记录 hot100(62,64,287,108)
算法·leetcode·职场和发展
王RuaRua3 小时前
[数据结构]5. 栈-Stack
linux·数据结构·数据库·链表
一只鱼^_3 小时前
牛客练习赛138(首篇万字题解???)
数据结构·c++·算法·贪心算法·动态规划·广度优先·图搜索算法
一只码代码的章鱼3 小时前
Spring的 @Validate注解详细分析
前端·spring boot·算法
邹诗钰-电子信息工程3 小时前
嵌入式自学第二十一天(5.14)
java·开发语言·算法
寒小松4 小时前
Problem E: List练习
java·数据结构·list
↣life♚4 小时前
从SAM看交互式分割与可提示分割的区别与联系:Interactive Segmentation & Promptable Segmentation
人工智能·深度学习·算法·sam·分割·交互式分割