Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to swap the addresses of two variables?

Tags:

c

pointers

swap

I know that it is possible to swap the value of two variables like so

#include <stdio.h>

void swap(int *x, int *y);
int main(){
    int x=5,y=10;
    swap(&x, &y);
    printf("x: %d, y: %d\n", x, y);
    return 0;
}

void swap(int *x, int *y){ 
    int temp;
    temp=*x;
    *x=*y;
    *y=temp;
}

But is it possible to swap the addresses of those two variables? And I don't mean just making a pointer to them and then swapping the values held by the pointers, I mean actually swapping the two, so that after the swap function the address of x is now the address of y before the swap function and vice versa.

I apologise if this is a silly question but I'm curious to see if such a thing is even possible. If this behaviour is not possible, why?


1 Answers

No, that's not possible. You don't get to choose the addresses of variables and you can't modify them either.

like image 123
fuz Avatar answered Sep 16 '25 23:09

fuz