Pointer basics (2)-pointers and functions
A pointer function
Return only functions whose type is a pointer
#include<stdio.h>
typedef int* Pint;
Pint function();
int main() {
Pint p = function();
printf("%d\n", *p); // 结果: 0(错误代码,但是VS2019可以正常运行)
printf("%d\n", *p); // 结果: 一串无意义的随机数
//此处function函数中的指针pn只能存活在函数一次调用结束
//因此这里仅仅验证函数可以返回指针类型
return 0;
}
Pint function() {
int num = 0;
int* pn = #
return pn;
}
note:
Using pointer functions, you can't return a pointer to the stack area (I don't understand the follow-up article here)
Two function pointers
Pointer to function type
#include<stdio.h>
void fun() {
printf("fun is been used!\n");
}
int function(char a, int n) {
printf("MuShan!!!\n");
return 0;
}
int main() {
// 返回值类型(*函数指针名)(形参类型)
int(*Pfunction)(char, int) = function;
char ch = 0;
int num = 0;
Pfunction(ch, num);
fun();
// 指针指向的类型* 指针名;
// void() ==> void(* )()
void(*pfun1)() = &fun; // pfun1: &fun ==> *pfun1: fun
void(*pfun2)() = fun; // pfun2: fun
(*pfun1)();
pfun1();
(*pfun2)();
pfun2();
// 都可正常输出
return 0;
}