更改局部变量的地址 [英] Changing the address of a local variable

查看:101
本文介绍了更改局部变量的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 xor算法交换两个局部变量,但是它不允许我更改变量的地址.如果我创建了指向变量的指针,它将允许它,但是不使用指针就可以做到这一点吗?

I want to swap two local variables using the xor algorithm, however it will not allow me to change the address of the variables. If I create pointers to the variables, it will allow it, but is it possible to do this without using pointers?

我正在尝试这样做

Point a = Point();
Point b = Point(1,1);

&a ^= &b;
&b ^= &a;
&a ^= &b;

这是我最想实现的目标

Point a = Point();
Point b = Point(1,1);

Point *a_ptr = &a;
Point *b_ptr = &b;

a_ptr = (Point *)(((unsigned long)a_ptr) ^ (unsigned long)b_ptr);
b_ptr = (Point *)(((unsigned long)a_ptr) ^ (unsigned long)b_ptr);
b_ptr = (Point *)(((unsigned long)a_ptr) ^ (unsigned long)b_ptr);

// The pointers are switched, but this will not work
&a = a_ptr;

推荐答案

C语言变量在运行时不像高级语言中的变量那样存在.对于编译器,局部变量"a"表示堆栈帧的地址-2"或任何其他值.该引用仅在编译时存在,并由声明固定.在运行时,生成的代码仅从硬编码的地址获取.因此,使用代码将变量指向不同的位置会尝试更改不存在的内容.

C language variables don't exist at runtime like variables in higher-level languages. Local variable "a" means, to the compiler, "the address of the stack frame - 2", or whatever it is. This reference exists only at compile time, and is fixed by the declaration. At runtime, the generated code simply fetches from the hard-coded address. So making the variable point to a different place with code is trying to change something that doesn't exist.

这篇关于更改局部变量的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆