Is it possible to swap the addresses of two variables?

前端 未结 3 1622
遥遥无期
遥遥无期 2021-01-15 16:10

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

#include 

void swap(int *x, int *y);
int main(){
    int x=5,y=10;
             


        
3条回答
  •  粉色の甜心
    2021-01-15 17:12

    At runtime, you do not have x or y any more. You have two memory addresses with sizeof int bytes reserved at each, which both are assumed to store an integer.

    You can swap the contents of these memory areas, and you can have pointer variables with their addresses, and can swap them, as you say. There really isn't any other meaningful way to swap anything here, so answer is "no", because concept of such swapping does not exist.

    I suppose, if you had virtual memory pages instead of just integers, then you could swap those, but even that would just be an efficient way to swap memory contents, as far application code is concerned.

    If you step outside of high level languages, then you could have self modifying code, where you would change the assembly code of the program to access y instead of x and vice versa. But conceptually this is same as having many pointers embedded into assembly, and changing the pointers. Also, very theoretical way, which requires writable code segment so not even possible in a modern OS without extra tricks.

提交回复
热议问题