[英]change the pointer referenced variable in a function
I have created a pointer variable to point to an active variable.我创建了一个指针变量来指向一个活动变量。 I have two variables, I want to toggle the active variable between these two variables.
我有两个变量,我想在这两个变量之间切换活动变量。 Managed to do this inside the main.
设法在主要内部做到这一点。 Now I want to extend this to another function
现在我想将其扩展到另一个功能
int main()
{
int x = 0;
int y = 0;
int *active=&y;
if(active == &x)
active = &y;
else
active = &x;
}
I dont want to swap the values of the variables, x, y.我不想交换变量 x、y 的值。
x, y are coordinates of a cartesian plane. x, y 是笛卡尔平面的坐标。
You can pass the reference of the pointer variable to the function, and in the formal parameter list create a pointer which holds the memory address of the pointer variable您可以将指针变量的引用传递给函数,并在形参列表中创建一个指针,该指针保存指针变量的内存地址
void flip(int **act, int *x, int *y){
if(*act == x){
*act = y;
}else{
*act = x;
}
}
int main()
{
int x = 0;
int y = 0;
int *active=&y;
flip(&active, &x, &y);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.