一直对c 的知识都是懵懵的,总是用着用着 开始觉的疑惑,然后就找找资料,现在就记录一下 函数指正 和 指针函数 的区别。
顺便记一下 : 现在耳机里的音乐是 river flows in you ---Yiruma
函数指针:本质是 指针变量 其指向的是函数
声明: 函数返回值类型 (*指针变量名)(函数参数) -------int (*FUNC)(int,int)
使用:FUNC =&test 假设有个函数 int test( int ,int )
实际上 FUNC ==* FCUN 在下面的程序中可以看到 它们打印的值相同
printf("cpp_func = %p\n", cpp_func);
printf("*cpp_func = %p\n", *cpp_func);
区别 是 FUNC 可以是左值 本质还是一个变量可以在 赋值符左边 但是*FUNC实际上 就是一个地址值 不能作为左值
cpp_func = (int (*)(int,int))dlsym(libCPPTest, "_Z4summii"); 是正确的
*cpp_func = (int (*)(int,int))dlsym(libCPPTest, "_Z4summii"); 是错误的
知乎上有见到:https://www.zhihu.com/question/29521437/answer/44649730
对于函数名: &函数名=*函数名=函数名
对于函数指针: *函数指针=函数指针 != &函数指针
这样说 也没错 但是使用时还是要 区别一下
指针函数:本质是一个函数 其返回值是一个某种类型的指针
声明 :指针类型名 *函数名 (函数参数) 或者这样要更专业些 ======= 类型标识符 *函数名 (函数参数)
使用:通常返回一个地址 如:常用于返回数组的某个元素的地址 或 值 (可以是多维数组)
#include<stdio.h>
int *f(int *b)
{
return (b+1);
}
int main(int argc,char** argv)
{
int *p;
int a[10]={1,2,3,1};
p=f(a);
printf("%p\n",p); //指针
printf("%d\n",*f(a)); //指针指向的值
printf("%d\n",*p); //指针指向的值
return 0;
}
//运行的结果
0xbfb09d9c
2
2
typedef:生成一个新的类型 -----用于自定的类型 系统的类型int 什么的就不用了哈
#include <dlfcn.h>
#include<stdio.h>
int main(int argc, char **argv)
{
void *libCPPTest = dlopen("./libTest.so", RTLD_NOW);
typedef int (*fun)(int,int);
// 2 fun *cpp_func;
// 2 *cpp_func = (int (*)(int,int))dlsym(libCPPTest, "_Z4summii");
fun cpp_func;
cpp_func = (int (*)(int,int))dlsym(libCPPTest, "_Z4summii");
//int (*cpp_func)(int,int) = (int (*)(int,int))dlsym(libCPPTest, "_Z4summii");
printf("cpp_func = %p\n", cpp_func);
printf("cpp_func output = %d\n", (*cpp_func)(10,10));
return 0;
}
/*
1.
ct@ubuntu:~/Desktop$ ./a.out
cpp_func = 0xb773952b
cpp_func output = 20
typedef int (*fun)(int,int) fun 新的类型 ---不再是变量 fun 为指针函数的类型
此时fun 可以声明 变量
fun func1
func1 =====int (*fun)(int,int)
2.
ct@ubuntu:~/Desktop$ ./a.out
cpp_func = 0xb7759000
cpp_func output = 20
而 fun *cpp_func; cpp_func这是一个二级指针 ,cpp_func指向的一个指针函数变量
*cpp_func = (int (*)(int,int))dlsym(libCPPTest, "_Z4summii"); *cpp_func 指针函数变量
为什么调用函数的时候 :
printf("cpp_func output = %d\n", (*cpp_func)(10,10));都是用这一条语句 不会出错呢?
应该就是这个原因叭:*函数指针=函数指针
此时的(*cpp_func)(10,10)就是函数指针
*/