method one:
The main function pointer is initialized, and the sub-function assigns the pointer value
#include <iostream>
using namespace std;
void sonFunc(int *c)
{
*c = 100;
printf("The value of the C is :%d\n",*c);
printf("The address of the C is :0x%x\n",c);
}
int main()
{
int a = 10;
int *b;
printf("The address of the A is : 0x%x\n", &a);
printf("The address of the B is : 0x%x\n", b);
/* 指针初始化 */
b = &a;
printf("The value of the B is : %d\n", *b);
printf("The address of the B is : 0x%x\n", b);
/* 传递int型指针b */
sonFunc(b);
printf("The value of the B is : %d\n", *b);
return 0;
}
Result: The address of pointer b after initialization is consistent with the address passed into the sub-function.
Method 2:
The main function defines an integer variable, passes the address of the integer variable, and the sub-function assigns a value to *(&a);
In the sub-function sonFunb(), the address assignment (locally effective) becomes effective after returning to the main function.
#include <iostream>
using namespace std;
void sonFunc(int *c)
{
*c = 100;
printf("The value of the C is :%d\n",*c);
printf("The address of the C is :0x%x\n",c);
}
void sonFunb(int *b)
{
int d = 111;
printf("The address of the B is : 0x%x\n", b);
printf("The address of the D is :0x%x\n",&d);
/* 子函数中地址赋值,不改变主函数中变量a的地址 */
b = &d;
printf("The address of the B is :0x%x\n",b);
printf("The value of the B is :%d\n",*b);
}
int main()
{
int a = 10;
printf("The address of the A is : 0x%x\n", &a);
/* 传递int型变量a的地址 */
sonFunb(&a);
printf("The address of the A is : 0x%x\n", &a);
printf("The value of the A is : %d\n", a);
/* 传递int型变量a的地址 */
sonFunc(&a);
printf("The address of the A is : 0x%x\n", &a);
printf("The value of the A is : %d\n", a);
return 0;
}
result:
The problem of passing parameters by function pointers is, in the final analysis, the problem of passing parameters. Some details are reflected in the code given above.