Regarding formal parameters and actual parameters, change the actual parameters

  c++, question

The change of formal parameters cannot affect the actual parameters, which I began to think. Later, it was discovered that using pointer variables can change arguments.

#include <stdio.h>
 #include<stdlib.h>
 
 void fun(int *a,int *b)
 {
 int *c;
 c=a;
 a=b;
 b=c;
 }
 
 void fun1(int *a,int *b)
 {
 int *c;
 *c=*a;
 *a=*b;
 *b=*c;
 }
 
 int main()
 {
 int  x=3, y=5, *p=&x, *q=&y,*k=&x,*z=&y;
 fun(p,q);    printf("%d,%d\n",*p,*q);
 fun1(k,z);  printf("%d,%d\n",*k,*z);
 // fun(&x,&y);   printf("%d,%d\n",*p,*q);
 return 0;
 }

This code outputs 3,53,3;

First of all, I think, in main (), p, q gets the address of shaping x, y. After entering the fun () function, the addresses of A, B and C exchanged by A, B and C should change as well as the addresses of P and Q, so I mistakenly believe that the outputs are 5 and 3.

As for entering the fun1 () function, the exchange of values of pointer variables should not change my erroneous belief that I should output 3,5. Please help me to guide and specify. Otherwise, I may not understand. Thank you

Func is a formal parameter, although the values of a and b have been changed (a, b is int * type, which is also the address you said (the address is also the value)), but it is not passed by reference, so it has no effect on p and q.

Func1 your int *c is assigned *c=*a without initialization; Are you sure you can run through?

void fun1(int *a,int *b)
 {
 int *c = new int;
 *c=*a;
 *a=*b;
 *b=*c;
 }

Func1 changes the values of *a and *b (*a refers to the contents of address a, that is to say, the contents of address a and the contents of address b are exchanged, and the overall operation at the memory level is valid), so the final output results are 5,3

How did you print your output 3,3? The main reason is that your program did not initialize the pointer. It must have thrown an exception.

For example, there are four values in the memory, A1->B1,A2->B2,A3->B3,A4->B4, where a is the address b is the value, B1=A3,B2=A4, which means A1 and A2 store A3, A4 pointers, A1, A2, A3, A4 respectively correspond to the p, q, x, y variables of your program

Enter func, p is transferred to a, A5->B1, q is transferred to b, A6->B2
Func is to exchange the values of a and b locally in the function, which corresponds to my example: A5->B2,A6->B1 exchanges the values of B1 and B2, but func exits the local variables to destroy A5, A6, leaving A1->B1,A2->B2,A3->B3,A4->B4

Enter func, p is transferred to a, A5->B1, q is transferred to b, A6->B2
The contents of a and b are exchanged (*a is the corresponding example A5->B1=A3->B3 for the contents of a address). after the exchange, A5->B1=A3->B4, A6->B2=A4->B3. look directly at A3 and A4 memory structures and change to A3->B4 and A4->B3
Exit local variable destruction A5, A6, leaving A1->B1,A2->B2,A3->B4,A4->B3