c指標在函式呼叫過程中的問題
阿新 • • 發佈:2019-02-07
</pre><p></p><pre name="code" class="cpp">#include <stdio.h>
#include <stdlib.h>
int *c;
void f(int *b)
{
int a = 10;
b = &a;
}
int main()
{
int tmp;
f(&tmp);
printf("%d\n",tmp);
return 0;
}
上面這段程式碼列印的結果是:2130567168
分析一下就可以知道,變數tmp的地址傳遞到函式f()中,指標b的值就是tmp的地址,後面b的值變成了a的地址,所以函式f()呼叫結束後,tmp地址存的值並沒有發生
變化。區域性變數未初始化,列印的值隨機。
稍微改一下:
#include <stdio.h>
#include <stdlib.h>
int *c;
void f(int *b)
{
int a = 10;
b = &a;
}
int main()
{
int *tmp;
f(tmp);
printf("%d\n",*tmp);
return 0;
}
這樣輸入的結果是:0
這個函式分析一下就是,指標tmp傳入函式f中的b變數,相當於b=tmp,隨後b=&a,這一過程tmp指標的內容並沒有發生改變,所以打印出來指標指向的地址值是隨機的
再修改一下程式:
#include <stdio.h>
#include <stdlib.h>
int *c;
void f()
{
int a = 10;
c = &a;
}
int main()
{
int *tmp;
f();
printf("%d\n",*c);
return 0;
}
這樣得到的結果是:10
這一過程指標c的值是a的地址,所以列印c指向的數值就是a的值
-------------------------------------------分割線--------------------------------------------------------------------------------
所以要想獲得a的值,要麼傳遞指標後,指標指向的地址存入a的值(而不是a的地址)
要麼就是獲得a的地址,通過return或者全域性變數