C语言,结构体,函数指针&&指针函数。

起因,写STM32屏幕菜单,找AI写了一段代码,发现是之前看过,忘记的,记录一下。

/* 1.结构体 */
typedef struct MenuPage{
    const char  *title;
    uint8_t      item_count;
    const char  **items;

    void (*on_select)(uint8_t index);
    void (*on_enter)(void);
    void (*on_exit)(void);

    /* NULL = 默认文字绘制 */
    void (*on_draw_item)(uint8_t index, uint16_t y, uint8_t selected);
} MenuPage;

这里的第一个 MenuPage 学名上叫标签。
第二个MenuPage叫别名,和下面一样
typedef struct{
    int id;
    int piece;
    int count;
}Product; // 这里的 Product 也叫别名。

const MenuPage page_relay = {
    .title        = "JIDIANQI",
    .item_count   = 11,
    .items        = relay_items,
    .on_select    = relay_on_select,
    .on_draw_item = relay_draw_item,
};

有标签就能在结构里面指向自己。
typedef struct MenuPage {
    int data;
    struct MenuPage *next;   // 只能用标签
} MenuPage_t;

MenuPage_t page = {
    .data = 100,
    .next = NULL   // 先赋 NULL,后面再修正
};
// 然后再让 next 指向自己
page.next = &page;

// 外部使用
MenuPage_t page1;            // 用别名
struct MenuPage page2;       // 也可以用标签(但不常见)


先复习一下结构体。

1 最简单版本
//先定义类型,再定义变量
struct Product{
    int id;         //编号
    int tick;       //节拍
    int interval;   //间隔
};

赋值方式
1
struct Product p1;
p1.id = 1;
p1.tick = 10;
p1.interval = 500;

2 初始化赋值
struct Product p1 = {2, 20, 800};
struct Product p1 = {.interval=300, .tick=5, .id=3};


第二种 定义类型同时创建变量
struct Product{
    int id;
    int piece;
}p1,p2;



第三种 别名
typedef struct{
    int id;
    int piece;
    int count;
}Product;

Product p1; //不用再加struct
Product p1 = {.id = 99, .piece=99, .count=99 };

函数指针 和 指针函数。

**先排除,指针函数**
#include <stdio.h>

// 定义一个指针函数:返回 int* 类型
int* getMax(int *a, int *b) {
    if (*a > *b) 
        return a;   // 返回 a 的地址
    else 
        return b;   // 返回 b 的地址
}

int main() {
    int x = 10, y = 20;
    int *p = getMax(&x, &y);   // p 指向较大的那个变量
    printf("%d\n", *p);        // 输出 20
    return 0;
}
getMax 是一个函数,它的返回值是指针(地址)。
调用它时,得到的是一个地址,需要再解引用才能拿到值。



**函数指针**
#include <stdio.h>

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

int main() {
    // 声明一个函数指针 p,指向参数为 (int,int)、返回 int 的函数
    int (*p)(int, int);
    
    p = add;              // 让指针 p 指向 add 函数
    int result = p(3, 5); // 通过指针调用函数,等价于 add(3,5)
    
    printf("%d\n", result);  // 输出 8
    return 0;
}

p 本身是一个变量,存储的是函数的地址。
可以通过 p(3,5) 调用它指向的函数。


// 
// 给函数指针类型起别名 p
typedef int (*p)(int, int);

int add(int a, int b) { return a + b; }

int main()
{
    p func_ptr;  // 用类型别名 定义 函数指针变量
    func_ptr = add;
    int res = func_ptr(3,4);
    return 0;
}

posted @ 2026-06-03 11:50  一见无始道成空  阅读(8)  评论(0)    收藏  举报