0

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.

1 Answer 1

1

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

}
Sign up to request clarification or add additional context in comments.

5 Comments

Maybe you meant void flip(int **act, int *x, int *y)?
Can you please submit you answer as well ? Here I have passed the reference of the pointer variable to the function
@NuOne, you have passed a pointer to the pointer variable to function flip. C does not have references. You have also passed pointers to main's local x and y variables. But the types of those arguments do not match the declared type's of flip()'s parameters, so the program has undefined behavior. Your compiler should at least be warning about that. If it isn't, then either turn up the warning level or get a better compiler. Your program might happen to work correctly on some systems, with some compilers, but it will definitely malfunction on others.
@JohnBollinger can you suggest an answer
@NuOne, Dmitri already told you how to correct your code. No other change is required.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.