1. 程式人生 > >C - 不傳引數修改函式外面的變數pass()

C - 不傳引數修改函式外面的變數pass()

今天一朋友給我看了一道題,很是鬼畜的題目。雖然知道應該沒有人會這麼寫程式碼,但是這裡面的邏輯還是很值得了解學習的。

程式碼填空:填寫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的地址。