Combination of pointers and functions
A first-class pointer as a formal parameter of a function
When the formal parameter of the function is an array, we define the function as follows:
grammar:
数据类型 函数名(数据类型 数组名)
For example :
void func(int a[],int a){
语句;
}
But in actual use, we usually define it in the form of a pointer , where the pointer a indicates that the data is an array type, for example:
void func(int *a,int n){
语句;
}
code show as below:
// 将数组的地址赋值给指针变量
int func(int *a,int n){
printf("wo%d",a[1]);
return 0;
}
int main(){
int b[] = {
1,2,3,3};
int c = 10;
func(b,c);
return 0;
}
When we call a function, we need to pass a string , which is how we can set the parameter type in the function tochar *变量
code show as below:
// 将传过来的字符串变量的地址赋值给指针变量p
int func1(char *p){
printf("%c\n",p[0]);
return 0;
}
int main(){
func1("hello");
return 0;
}
Tip : If the formal parameter of the function is a pointer, we generally judge the value of the pointer first to determine whether the value of the pointer is NULL.
secondary pointer
Use a pointer variable to save the address of a first-level pointer variable, which we call a second-level pointer .
grammar:
数据类型 **变量名
Examples are as follows:
int a = 10;
int *p = &a; // p为一级指针保存变量a的地址
int **pp = &p; // pp为二级指针,保存一级指针p的地址
Here you can think of it as an array of pointers, put all pointer variables (first-level pointers) in an array, and then assign the pointer variables in the array to another pointer variable (secondary pointer) in turn.
code show as below:
int main(){
int a = 10;
int *p = &a;
int **pp = &p; // 指针pp保存了指针p的地址
printf("%d\n",*p);
printf("%d\n",**pp);
printf("%p\n",*pp); // 二级指针pp保存的地址
printf("%p\n",p); // 一级指针p的地址
// 这里就相当于
// &a == p == *pp
// a == *p == **pp
return 0;
}