Detailed explanation of pointers in C language (4)

Table of contents
Key points of this chapter
1. Character pointer
2. Array pointer
3. Array of pointers
4. Array parameter passing and pointer parameter passing
5. Function pointer
6. Array of function pointers
7. Pointer to array of function pointers
8. Callback function
9. Analysis of pointer and array interview questions
function pointer
array pointer — a pointer to an array
function pointer — pointer to a function
function pointer
Let's look at the code
#include<stdio.h>
int Add(int x, int y)
{

}
int main()
{
	int a = 10;
	int b = 20;
	int arr[10] = { 0 };
	printf("%p\n", &Add);
	printf("%p\n", Add);
	return 0;
}

Remember here, there is no first element and the address of the first element in a function, & the function name and function name are both functions

Then look at the following code

#include<stdio.h>
int Add(int x, int y)
{
	int z = 0;
	z = x + y;
	return z;
}
int main()
{
	int a = 10;
	int b = 20;
	int arr[10] = { 0 };
	int(*pa)(int, int) = Add;
	printf("%d\n", (*pa)(2, 3));
	/*printf("%p\n", &Add);
	printf("%p\n", Add);*/
	return 0;
}

The result is 5. Let me explain the meaning of the above code here. First, we add a () to indicate that pa is a pointer, put the address of the function in pa, and then explain that the value we want to pass is (2, 3) , I hope everyone can understand

Let's look at the code next 

#include<stdio.h>
void Print(char* str)
{
	printf("%s\n", str);
}
int main()
{
	void(*p)(char*) = Print;
	(*p)("hello bit");
	return 0;
}

This is the concept of our function pointer

The output is two addresses, which are the addresses of the test function. So how do we save the address of our function if we want to save it? Let's look at the code below:
void test()
{
	printf("hehe\n");
}
//下面pfun1和pfun2哪个有能力存放test函数的地址?
void (*pfun1)();
void* pfun2();
First of all, if the storage address can be given, pfun1 or pfun2 is required to be a pointer, so which one is a pointer? the answer is:
pfun1 can be stored. pfun1 is first combined with * , indicating that pfun1 is a pointer, the pointer points to a function, the pointed function has no parameters, and the return value type is void
pfun2 is first combined with (), he is not a pointer, just a function name
The end of this chapter!
In the next chapter, we will talk about two examples related to this blog, and then we will talk about arrays of function pointers

 

 

Guess you like

Origin blog.csdn.net/fjj2397194209/article/details/131221150