指针函数与函数指针

函数指针:

对于编译器来说,所有的定义都可以用“变量”来表示,而在C/C++中,拥有强大的地址变量工具,指针。你可以通过指针调用变量,包括定义的指针类型的函数,这里的指针函数具有直接赋值调用的寻址方式。
注:本人开发环境为qtcreator,各位读友可以自动屏蔽环境差别。

代码如下:

//#include <QCoreApplication>

#include <stdlib.h>
#include <stdio.h>
#include <QString>

void output(char* a)
{
    printf("output %s",a);
    return;
}

typedef void (*P_Fun)(char *);

int main(int argc, char *argv[])
{
//    QCoreApplication a(argc, argv);
//    return a.exec();
      char* a="Print call function";
      void (*P_Fun_one)(char *)=output;
      P_Fun_one(a);
      return 0;
}

执行结果如下:

这种实例的运用方式可能在一些底层代码中见到较多,例如Linux内核源码中。

这种调用的方式可以是这样的调用。如下

1.function.dll &&function.h,首先dll函数是普通函数。

2.U_project (你的源码)。

 

在你的源码中可以定义

typedef (* Functio_name)(argument) 这样的函数类型

然后赋值调用。

然后想发现新大陆一样,比如现在有一个容器类,里面赋值的都是函数的地址,那么通过索引调用,可以实现一个容器的顺序调用:

这样可以通过封装后的list进行函数调用。

//#include <QCoreApplication>

#include <stdlib.h>
#include <stdio.h>
#include <QString>

void output(char* a)
{
    printf("output %s\n",a);
    return;
}

typedef void (*P_Fun)(char *);
typedef void (*P_Fun1)();

void out_one()
{
    printf("out_one\n");
}

void out_two()
{
    printf("out_two\n");
}

void out_three()
{
    printf("out_three\n");
}

P_Fun1* b[3]={NULL};

void addlist_pointer(/*P_Fun1* pointer*/)
{
    int i=0;
    for(i;i<=2;i++)
    {
        switch (i) {
        case 0:
            {
            static P_Fun1 one_F=out_one;
            b[i]=&one_F;
            printf("add addr is (%d->%d)\n",&one_F,out_one);
            break;
            }
        case 1:
            {
            static P_Fun1 tow_F=out_two;
            b[i]=&tow_F;
            printf("add addr is (%d->%d)\n",&tow_F,out_two);
            break;
            }
        case 2:
            {
            static P_Fun1 three_F=out_three;
            b[i]=&three_F;
            printf("add addr is (%d->%d)\n",&three_F,out_three);
            break;
            }
        }
    }
     printf("%d\n",*b[2]);
}

void calllist_pointer()
{


}

int main(int argc, char *argv[])
{
      char* a="Print call function\n";
      void (*P_Fun_one)(char *)=output;
      P_Fun_one(a);

      addlist_pointer();
      printf("%d\n",*b[2]);

      printf("call list addr is %d,%d,%d\n",b[0],b[1],b[2]);

      printf("%d\n",*b[2]);

      printf("call *L[] addr is %d,%d,%d\n\n",*b[0],*b[1],*b[2]);

      int i=0;



      for(i;i<=2;i++)
      {
          P_Fun1(*(P_Fun1*)b[i])();
      }
      return 0;
}

发现了一个问题 在addlist_pointer函数里面有一个static 的声明,去掉二级指针指向的地址会自动改变。

估计指针入栈被系统释放掉了。所以加上static 定义到静态区。

结果如下:

指针函数:

int * function(){}

char* function(){}

double* function() {}

这种返回值为指针的函数,叫做指针函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值