当前位置:网站首页>C language helps you understand pointers from multiple perspectives (1. Character pointers 2. Array pointers and pointer arrays, array parameter passing and pointer parameter passing 3. Function point
C language helps you understand pointers from multiple perspectives (1. Character pointers 2. Array pointers and pointer arrays, array parameter passing and pointer parameter passing 3. Function point
2022-07-07 20:30:00 【Zhu C】
Catalog
2. Array pointer and pointer array :
5. A pointer to an array of function pointers :
1. Character pointer :
Character pointer , seeing the name of a thing one thinks of its function , Pointer to character data , It is also the simplest kind of pointer introduced in this article , But there are a few fallible points , So take this opportunity to explain in detail . The following is the simplest use of character pointers
int main()
{
char ch = 'w';
char *pc = &ch;
*pc = 'w';
return 0; }besides , We often encounter situations where character pointers point to strings :
int main()
{
const char* pstr = "hello world.";
printf("%s\n", pstr);
return 0; }Here is to put a string into pstr Is it in the pointer variable ?
Obviously not , But why can I print this string ?
as a result of , The character pointer stores the address of the first element of the string , then printf Function %s Look down with the address of the first element , Print out the whole string . therefore , in fact , The character pointer only stores the address of the first element of the string .
Now let's give a topic , Consolidate the most important points of character pointer :
#include<stdio.h>
int main()
{
char str1[] = "hello world.";
char str2[] = "hello world.";
const char* str3 = "hello world.";//3 4 Constant string , Cannot be changed , In the read-only data area
const char* str4 = "hello world.";
if (str1 == str2)// The array name is the first element address ,
//1 and 2 Are two separate arrays , So the first address is different
printf("str1 == str2\n");
else
printf("str1 != str2\n");
if (str3 == str4)// explain str3 and str4 Point to the same string , All are a The address of
printf("str3 == str4\n");
else
printf("str3 != str4\n");
return 0;
}
2. Array pointer and pointer array :
Understanding pointers in depth can avoid distinguishing pointer arrays from array pointers and learning to apply .
First of all, it is clear that the array pointer is The pointer ! Pointer array is used to store pointers Array !
// Pointer array :
int *p1[10];
// Array pointer :
int (*p2)[10];Explanation of array pointer :
#include <stdio.h>
int main()
{
int arr[10] = {0};
printf("%p\n", arr);
printf("%p\n", &arr);
return 0; } 

Here we find ,&arr Actually arr The address of the entire array ,+1 Then skip the length of the entire array .
#include <stdio.h>
int main()
{
int arr[10] = {1,2,3,4,5,6,7,8,9,0};
int (*p)[10] = &arr;// Put the array arr To an array pointer variable p
// But we seldom write code like this
return 0; }#include <stdio.h>
void print_arr1(int arr[3][5], int row, int col) {
int i = 0;
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
void print_arr2(int (*arr)[5], int row, int col) {
int i = 0;
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
int main()
{
int arr[3][5] = {1,2,3,4,5,6,7,8,9,10};
print_arr1(arr, 3, 5);
// Array name arr, Represents the address of the first element
// But the first element of a two-dimensional array is the first row of a two-dimensional array
// So the message here is arr, It's actually equivalent to the address on the first line , Is the address of a one-dimensional array
// You can use an array pointer to receive
print_arr2(arr, 3, 5);
return 0; }The array pointer is used in the parameter passing of the second code , Please pay attention to the difference between the two
3. A function pointer :
For different functions , In fact, we can also point to the corresponding function with a pointer , And it is used to call the function by dereferencing the function pointer , Here is a simple example for understanding :
int Add(int x,int y)
{
return x + y;
}
int main()
{
int arr[5] = { 0 };
int(*p)[5] = &arr;// Array pointer
//& Function name -- What you get is the address of the function ?
printf("%p\n", &Add);// Functions have addresses
printf("%p\n", Add);// There is no difference between the two ,& Function name and function name are the address of the function
int (*pf)(int, int) = &Add;// Similar to array pointers
int ret=(*pf)(2, 3);//Add(2,3)
int ret = pf(2, 3);// It's fine too
printf("%d\n", ret);
return 0;
}We compare array pointers , After the array pointer [ ] Replaced by the function used ( ) It is roughly the rudiment of function pointer , Form like
int(*pf)(int x,int y) there * Express pf Is a pointer ,( ) Indicates a pointer to a function .
#include <stdio.h>
void test()
{
printf("hehe\n");
}
int main()
{
printf("%p\n", test);
printf("%p\n", &test);
return 0; }
Through this function and output, we found that in fact, functions also have addresses , This also proves the rationality of the existence of function pointers . A preliminary understanding of function pointers lays the foundation for the three categories we will introduce below .
4. Function pointer array :
Function pointer array , Through our understanding above , Is an array of function pointers , Then how to write its form ? Now we give :int (*parr1[10])();
In fact, it is not difficult for us to figure out , Put an array on the basis of the function pointer , So this array is used to store function pointers . Next, we give an example of implementing a computer to further explain the function pointer array ( The calculator is relatively simple , An example intended to implement a function pointer array ):
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
int main()
{
int x, y;
int input = 1;
int ret = 0;
int(*p[5])(int x, int y) = { 0, add, sub, mul, div }; // Transfer table
while (input)
{
printf("*************************\n");
printf(" 1:add 2:sub \n");
printf(" 3:mul 4:div \n");
printf("*************************\n");
printf(" Please select :");
scanf("%d", &input);
if ((input <= 4 && input >= 1))
{
printf(" Enter the operands :");
scanf("%d %d", &x, &y);
ret = (*p[input])(x, y);
}
else
printf(" Incorrect input \n");
printf("ret = %d\n", ret);
}
return 0;
}Note that the function pointer array is used in the middle of the transfer table , It can point to the corresponding function implementation .
5. A pointer to an array of function pointers :
With the above, we understand , We can try to write out the form of pointers to the array of function pointers ,
Let's dissect :
The pointer to the array of function pointers is a The pointer
void test(const char* str) {
printf("%s\n", str);
}
int main()
{
// A function pointer pfun
void (*pfun)(const char*) = test;
// An array of function pointers pfunArr
void (*pfunArr[5])(const char* str);
pfunArr[0] = test;
// Pointer to function array pfunArr The pointer to ppfunArr
void (*(*ppfunArr)[5])(const char*) = &pfunArr;
return 0; }Here we have a brief understanding , Finally, we give the implementation process of the callback function , This is the most important example , It is also a classic with technical content in pointer .
6. Callback function :
Definition :
We borrow qsort Function , And do it yourself qsort Function to call back
// Bubble sort can only sort integer data
//void bubble_sort(int arr[],int sz)
//{
// int i = 0;
// int j = 0;
//for(i=0;i<sz-1;i++)
//{int flag = 1;// Suppose the array is well ordered
// for (j = 0;j<sz-i-1;j++)
// {
//
// if (arr[j] > arr[j + 1])
// {
// int tmp = arr[j];
// arr[j] = arr[j + 1];
// arr[j + 1] = tmp;
// flag = 0;//
// }
// }
// if(flag==1)
// {
// break;
// }
//}
//}
//qsort Library function A sort function implemented using the idea of quick sort
// You can sort any type of data
//
//
//void qsort(void* base,// The starting position of the data you want to sort
//size_t num,// The number of data elements to be sorted
//size_t width, // The size of the data elements to be sorted
//int(* cmp)(const void* e1, const void* e2)// A function pointer , It's a comparison function
//);
// Compare two shaping elements
//e1 Point to an integer
//e2 Point to an integer
int cmp_int(const void* e1, const void* e2)
//{
// if (*(int*)e1 > *(int*)e2)// Cast
// return 1;
// else if (*(int*)e1 == *(int*)e2)
// return 0;
// else
// return -1;
//}
//
{return *(int*)e1 - *(int*)e2; }// Cast
void Swap(char* buf1, char* buf2, int width)
{
int i = 0;
for (i = 0; i < width; i++)
{
char tmp = *buf1;
*buf1 = *buf2;
*buf2 = tmp;
buf1++;
buf2++;
}
}
//void* It cannot be dereferenced directly
//void Is a pointer without a specific type , Can accept any type of pointer
// No specific type , So you can't dereference , Also can not +- Integers
void bubble_sort(void* base, int sz, int width, int(*cmp)(const void* e1, const void* e2))
{
int i = 0;
// Number of trips
for (i = 0; i < sz - 1; i++)
{
int flag = 1;// Suppose the array is well ordered
// A bubble sorting process
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (cmp((char*)base + j * width, (char*)base + (j + 1) * width) > 0)
{
// In exchange for
Swap((char*)base + j * width, (char*)base + (j + 1) * width, width);
flag = 0;
}
}
if (flag == 1)
{
break;
}
}
}
struct Stu
{
char name[20];
int age;
};
int cmp_stu_by_name(const void* e1,const void* e2)
{
return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);
}
void test1()
{
int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
// Arrange the array in ascending order
int sz = sizeof(arr) / sizeof(arr[0]);
//bubble_sort(arr, sz);
qsort(arr, sz, sizeof(arr[0]), cmp_int);// Default ascending
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
void test2()
{// Test use qsort To sort structure data
struct Stu s[] = { {"zs",15 }, { "ls",30 }, { "ww",25 } };
int sz = sizeof(s) / sizeof(s[0]);
qsort(s, sz, sizeof(s[0]),cmp_stu_by_name);
}
void test3()
{
int arr[] = { 9,8,7,6,5,4,3,2,1,0 };
// Arrange the array in ascending order
int sz = sizeof(arr) / sizeof(arr[0]);
//bubble_sort(arr, sz);
bubble_sort(arr, sz, sizeof(arr[0]), cmp_int);// Default ascending
int i = 0;
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
void test4()
{
// Test use qsort To sort structural data
struct Stu s[] = { {"zhangsan", 15}, {"lisi", 30}, {"wangwu", 25} };
int sz = sizeof(s) / sizeof(s[0]);
bubble_sort(s, sz, sizeof(s[0]), cmp_stu_by_name);
//bubble_sort(s, sz, sizeof(s[0]), cmp_stu_by_age);
}
int main()
{
//test1();
//test2();
test3();
test4();
}Here we give detailed code comments in the code . Here we are mainly in bubble_sort Callback in function cmp_XX Corresponding function , Please also understand carefully .
The above is the content of the advanced pointer , In the future, we will use this knowledge many times in the data structure . Hope to help you !
边栏推荐
- Phoenix JDBC
- Small guide for rapid formation of manipulator (11): standard nomenclature of coordinate system
- POJ 1742 Coins ( 单调队列解法 )「建议收藏」
- Tensorflow2. How to run under x 1 Code of X
- Numerical method for solving optimal control problem (0) -- Definition
- Implement secondary index with Gaussian redis
- Micro service remote debug, nocalhost + rainbow micro service development second bullet
- 4G设备接入EasyGBS平台出现流量消耗异常,是什么原因?
- Don't fall behind! Simple and easy-to-use low code development to quickly build an intelligent management information system
- 取两个集合的交集
猜你喜欢

使用高斯Redis实现二级索引

Helix QAC 2020.2 new static test tool maximizes the coverage of standard compliance

【论文阅读】MAPS: Multi-agent Reinforcement Learning-based Portfolio Management System

One click deployment of any version of redis

Make this crmeb single merchant wechat mall system popular, so easy to use!

AIRIOT助力城市管廊工程,智慧物联守护城市生命线

上海交大最新《标签高效深度分割》研究进展综述,全面阐述无监督、粗监督、不完全监督和噪声监督的深度分割方法

How does codesonar help UAVs find software defects?

AADL inspector fault tree safety analysis module
Klocwork code static analysis tool
随机推荐
【函数递归】简单递归的5个经典例子,你都会吗?
Cantata9.0 | new features
Codesonar enhances software reliability through innovative static analysis
Helix QAC 2020.2新版静态测试工具,最大限度扩展了标准合规性的覆盖范围
One click deployment of any version of redis
让这个CRMEB单商户微信商城系统火起来,太好用了!
Optimization cases of complex factor calculation: deep imbalance, buying and selling pressure index, volatility calculation
Useful win11 tips
EasyGBS级联时,上级平台重启导致推流失败、画面卡住该如何解决?
Apifox 接口一体化管理新神器
Make this crmeb single merchant wechat mall system popular, so easy to use!
Phoenix JDBC
AIRIOT助力城市管廊工程,智慧物联守护城市生命线
【解决】package ‘xxxx‘ is not in GOROOT
想杀死某个端口进程,但在服务列表中却找不到,可以之间通过命令行找到这个进程并杀死该进程,减少重启电脑和找到问题根源。
图扑数字孪生煤矿开采系统,打造采煤“硬实力”
Read PG in data warehouse in one article_ stat
写了个 Markdown 命令行小工具,希望能提高园友们发文的效率!
How C language determines whether it is a 32-bit system or a 64 bit system
复杂因子计算优化案例:深度不平衡、买卖压力指标、波动率计算