[英]Copying Value of a pointer to a variable, Pointer is passed as an argument C Program
[英]Pointer to an argument passed as value?
在下面的示例中:
#include <stdio.h>
#include <stdlib.h>
void test1 (int x)
{
int * xp = &x;
printf("Address of xp (test1): [%p]\n", &xp);
printf("xp points to: [%p] which is the same as [%p]\n", xp, &x);
}
int main()
{
int x = 4;
printf("Address of x (main): [%p] \n", &x);
test1(x);
return 0;
}
輸出:
Address of x (main): [0xbfca0c5c]
Address of xp (test1): [0xbfca0c2c]
xp points to: [0xbfca0c40] which is the same as [0xbfca0c40]
0xbfca0c40
(test1中參數的地址)會發生什么? 那是由實現定義的。
這很可能在機器堆棧上,因為堆棧是實現參數傳遞和局部變量的非常常見的方式。 當test1()
函數退出時,將釋放堆棧空間,因此可以重新使用有問題的內存。
int x;
在test1
形式參數列表中,是test1
局部變量。 它的狀態與您是否也曾去過類似int y;
作為test1
內的聲明。 它具有自動存儲期限。
test1
退出后,該變量不再存在。
通常,編譯器通過包含堆棧結構的內存塊來實現自動存儲 。 當您調用一個函數時,該函數的自動變量(以及返回地址和任何需要保存的寄存器)將在堆棧頂部聲明新的空間; 當您離開該函數時,堆棧會“彈出”回到調用該函數之前的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.