Pointer parameter transfer in C language
1. How to change the value of the parameter
1. Common mistakes in writing:
The following function cannot change the value of a since the variable will be destroyed as the stack exits.
#include<stdio.h>
void f(int b){
//参数b初始化为1
b=3;//改变b的值为3
}//随着函数的结束,变量b被销毁,a的值并没有发生改变
int main(void){
int a=1;
f(a);//将a的值传入函数
printf("a的值为:%d",a);
}
operation result:
a的值为:1
2. The solution is to use pointers
#include<stdio.h>
void f(int *ptr){
//ptr的值等于变量a的地址
*ptr=3;//对ptr间接访问,相当于变量a,这里把3赋值给变量a
}
int main(void){
int a=1;
f(&a);//将a的地址传入
printf("a的值为:%d",a);
}
operation result:
a的值为:3
2. Compare with return
1. Use return to return the value:
#include<stdio.h>
int f(){
int a=3;
return a;
}
int main(void){
int a=1;
a=f();
printf("a的值为:%d",a);
}
operation result:
a的值为:3
It can be seen that the value of a can also be changed using return, but unlike a pointer, it can only return one value.
Using a pointer, the values of multiple variables can be changed at the same time, as follows:
2. Use pointers to change the value of multiple parameters
#include<stdio.h>
void f(int *ptr1,int *ptr2){
*ptr1=3;
*ptr2=3;
}
int main(void){
int a=1;
int b=1;
f(&a,&b);
printf("a的值为:%d\n",a);
printf("b的值为:%d\n",b);
}
operation result:
a的值为:3
b的值为:3
3. How to change the value of the pointer?
pointers using pointers
#include<stdio.h>
void f(int **ptr){
//ptr初始化为b的地址
*ptr=NULL;//对ptr进行间接访问,得到的是指针b,把它赋值为NULL
}
int main(void){
int a=1;
int *b=&a;
printf("a的地址为:%d\n",&a);//打印a的地址
printf("b的值为:%d\n",b);//此时b指向a,打印的是a的地址
f(&b);
printf("b的值为:%d\n",b);//此时指针b的值已经改变了,为NULL
}
operation result:
a的地址为:6422264
b的值为:6422264
b的值为:0