noone
noone

Reputation: 6558

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 are coordinates of a cartesian plane.

Upvotes: 0

Views: 43

Answers (1)

noone
noone

Reputation: 6558

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);

}

Upvotes: 1

Related Questions