1
int fun(int x);

int main()
{
    fun(10);
    fun(11);   
    return 0;
}

int fun(int x)
{
    int loc;//local variable
    cout<<&loc;
    return 0;
}

出力は

0xbfb8e610 
0xbfb8e610

ここで loc はローカル変数であり、関数の最初の実行後にスコープ外になりf(10)、次の実行のために再び割り当てられfun(11)ます。locしたがって、私の理解では、変数のアドレスは異なる必要があります。&locでは、なぜ両方の実行でアドレスが同じなのですか?

4

3 に答える 3

7

Each invocation of fun needs its own place to store the variable. But as soon as the function returns, the variable no longer exists. There's no reason the address can't be re-used. It doesn't have to be, but there's no reason it can't be.

In a typical implementation, stack space is used to hold the information needed to return from a function and their local variables when a function is invoked. When the function returns, the local variables are removed from the stack and the return information popped off it, leaving the stack back where it was when the function was called. Since the two function invocations are the same, they wind up with the stack the same in both cases, making the local variable have the same address. This is what an experienced programmer would would expect, but not rely on.

于 2013-02-08T07:55:32.413 に答える
3

スタック上で何が起こっているかをやや単純化した (あいまいな) イラスト。

main()0xtopomain一定のままであると仮定):

   ~Stack~
==============
= 0xtopomain =
= 0x........ =
==============

fun()(プッシュ)の最初の実行:

   ~Stack~
==============
= 0xothers.. =
= 0xbfb8e610 = <- loc
= 0xmemoffun = <- other memory allocated for fun()
= 0xtopomain =
= 0x........ =
==============

(ポップ)に戻るmain():

   ~Stack~
==============
= 0xtopomain = <- Where the hell is loc?!!
= 0x........ =
==============

2 回目の実行fun()(もう一度押す):

   ~Stack~
==============
= 0xothers.. =
= 0xbfb8e610 = <- loc's here again
= 0xmemoffun = <- other memory allocated for fun()
= 0xtopomain =
= 0x........ =
==============
于 2013-02-08T08:07:11.083 に答える
2

スタックに格納されたローカル変数 (新しくプッシュされた変数が一番上に、古い変数が一番下にある特別なメモリ領域)。関数を呼び出すと、戻りアドレス、パラメーター、レジスターなどを保存するなど、いくつかの操作が行われます。ただし、順序があります。そして、戻り時に、プッシュされたすべての変数がスタックからポップされました。同じ関数を使用していて、2 つの呼び出しの間にあるため、メイン関数でローカル変数を使用しないでください。これは、変数のアドレスが同じであることが予想されます。

于 2013-02-08T07:57:54.970 に答える