函数指针,与c++类的联想

本文展示了一个使用C语言实现的简单命令解析器,通过定义命令结构体和函数指针,实现了不同命令的动态调用。文章详细介绍了如何创建一个包含命令名、执行函数和帮助信息的结构体数组,并在主函数中遍历执行每个命令。此外,还提供了三个示例命令:显示固件版本、闪存测试和结束命令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>


typedef void (*functionPointerType)(void);
typedef struct commandstruct
{
    char const* name;
    functionPointerType Pfunction;
    char const *help;    
};
void commVersion();
void cmdend();
void cmdflashtest();

const struct commandstruct commandstruct[]=
{
    {"ver",&commVersion,"display firmware version"},
        {"flash test",&cmdflashtest,"flash test"},
            {"end",&cmdend,"end"}
};
3

void main()
{
    int i=0;
    for(i=0;i<3;i++)
    {
        commandstruct[i].Pfunction();        
    }
}

void commVersion()
{
    int i=0;
    for(i=0;i<3;i++)
    {
        if(commandstruct[i].Pfunction==&commVersion)
        {
            printf("%s",commandstruct[i].help);        
            break;
        }
    }    
}

void cmdflashtest()
{
    int i=0;
    for(i=0;i<3;i++)
    {
        if(commandstruct[i].Pfunction==&cmdflashtest)
        {
            printf("%s",commandstruct[i].help);        
            break;
        }
    }
    
}
void cmdend()
{
    int i=0;
    for(i=0;i<3;i++)
    {
        if(commandstruct[i].Pfunction==&cmdend)
        {
            printf("%s",commandstruct[i].help);        
            break;
        }
    }
}

联想到c++虚函数,通过指针的变换,决定执行对应虚函数 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值