The function that returns a pointer and the use of a pointer to a function
#include <stdio.h>
#include <stdlib.h>
void *func () {
/*
* A very easy mistake to return the address of the local variable
*/
int m;
printf ("Define as void *func ()/n");
return &m;
}
/*
* Declares a pointer to a function pointing to a function that returns a type void pointer
*/
void * (*pfunc) ();
/*
void (*pfun) ();
* Declare a function that points to a function that returns void. Actually this and the first kind of
* void *func () is the most easily confusing way for most people. The summary will introduce
* Method of discrimination. Because this kind of pointer has been said before, here is not an example.
*/
int main () {
int *result;
pfunc=func;/* Assignment * /
result= (int *) func ();/* Convert void* to int**/
func ();
Pfunc ();
return 0;
}
/*
* Compile the above program, can "normal" pass, but will be warned: returned temporary local variables
* address, because local variables are placed in the stack and are automatically released at the end of the function, if you really want to
* Use local variables in the function to return, you can use malloc to allocate memory addresses, malloc
* Allocated memory belongs to the heap segment of the process, it needs to be freed itself, or the program runs at the end of the C runtime
* to release.
* Finally, tell me how to distinguish between these two things
* Char *func ();
* CHAR (*FUNC) ();
* Remember that the binding of the function () is higher than the pointer *, it can be easily distinguished, because () is higher than *, so
* The variable func in char *func () is a function that is further compared to the normal function char func ()
* You can consider char in Char *func () to be enclosed in parentheses. and
* func in char (*func) (), because of parentheses, so first with the pointer *, becomes a
* pointers, just as functions in the normal functions char function () are actually also a function pointer
* Same, so you can think of (*func) as a normal variable.
*/
The function that returns a pointer and the use of a pointer to a function