今天一朋友给我看了一道题,很是鬼畜的题目。虽然知道应该没有人会这么写代码,但是这里面的逻辑还是很值得了解学习的。
代码填空:填写pass()函数。
要求输出:456
#include "stdio.h"
void pass(){
}
int main(){
int x = 123;
pass();
printf("%d\n",x);
getchar();
}
刚看到这道题,心里一句mmp。
仔细思考,原来是考的内存地址的知识。
废话不多说,直接上代码
#include "stdio.h"
void pass(){
int temp = 0; // 定一个变量为temp
int *p = &temp; // 取temp的地址p
while (*p!=123){ // 比较*p和x的值,让p移动到x的地址,
p++;
}
*p = 456; // 修改当前地址的值,也就是x的值。
}
int main(){
int x = 123;
pass();
printf("%d\n",x);
getchar();
}
我们知道c语言的变量地址是先存放高地址,逐渐变小。栈区在堆区上面,也就是栈区的地址大于堆区。
使用p使用向上加来寻找x的地址。