C/c++ pointer parameter passing example

I am a sophomore student. I have been learning programming for a year. I would like to share the technology with you in the form of a blog. If there is something wrong with me, I welcome everyone to correct me.
Today, one of my seniors asked me about the change of pointer passing value. I decided to share the question asked by my brother today with you in code.

Stop talking nonsense, let's get to the code.
1) In the first case, the function parameter is a pointer, and the value is assigned in this way

void test(int* arr){
int a=3;

arr = &a;

}

int main(void){

int value = 0;
int *arr = &value;

printf("函数调用前:*arr=%d\n",*arr);
//test(arr);
printf("函数调用后:*arr=%d\n",*arr);


system("pause");
return 0;
}
大家觉得这个value传入前后值是否会改变,答案当然是不会改变!
好让我们看看在vs2010上的执行情况

!Insert picture description here

2) Here we noticed that the parameter pointer in the test() function is a new pointer created in the temporary function. In this way, we are equivalent to the pointer assignment, that is, the arr pointer in the test function = the arr pointer in the main function , After the assignment, the assignment operation is performed on it, in fact, the assignment operation is already performed on this temporary pointer, and it has nothing to do with the original main function pointer.
So if we want to change the incoming value by passing parameters, we can use this method.
Just add an address character, and the result will be very different.

void test(int* &arr){
int a=3;
arr = &a;

}

int main(void){

int value = 0;
int *arr = &value;

printf("函数调用前:*arr=%d\n",*arr);
//test(arr);
printf("函数调用后:*arr=%d\n",*arr);
system("pause");
return 0;
}

Insert picture description here

3) We have seen that the value of arr has changed. Because the parameter in the test() function is no longer a copy of the main function at this time. Both of them are equivalent.
In fact, there is another way to play. You can change
the value of arr without adding references and you can also change the value of value
void test(int * arr){ int a=3;

*arr = a;

}

int main(void){

int value = 0;
int *arr = &value;

printf("函数调用前:*arr=%d\n",*arr);
printf("函数调用后:*value=%d\n\n",value);
test(arr);
printf("函数调用后:*arr=%d\n",*arr);

printf("函数调用后:*value=%d\n",value);

system("pause");
return 0;
}
我们看下在vs2010的执行情况

Insert picture description here

Why does this happen? The arr of the sub-function here is also a copy of the main function, but why it can change the value of arr and change the value of value, that is because in the sub-function *arr=a ; Actually operate directly on the value of value!
That's it for today's pointer sharing. If you have any questions, you can communicate with me.

Guess you like

Origin blog.csdn.net/weixin_45825875/article/details/108412033