我對以下代碼有疑問。我不確定為什么存盤在 yAdd 中的地址沒有更新為存盤在下面代碼中 addfun() 函式內的變數 x 中的相同地址?我的想法有什么問題?
#include <iostream>
using namespace std;
void fun(int *x) {
*x = 55;
}
void addfun(int **x) {
*x = new int[3];
cout << x << endl; // x stores the address of int[0]
// say it is 0x7ffc32e646a0
cout << &x << endl;
}
int main()
{
int y = 99;
int *yAdd = &y;
cout << y << endl;
fun(yAdd);
cout << y << endl;
cout << yAdd << endl; // original address stored in yAdd
cout << "address of y is " << &y << endl;
addfun(&yAdd); // so I update the address stored in yAdd to be the same address
// as stored inside the x in the addfun function
cout << yAdd << endl; // but how come when printing this, yAdd doesn't
// show 0x7ffc32e646a0, but something else?
return 0;
}
uj5u.com熱心網友回復:
addfun(&yAdd);
這是將地址yAdd作為引數傳遞給該函式。
yAdd是一個指標。指標是程式中某個其他物件的地址。該物件是什么并不重要,yAdd 是它的指標,無論yAdd它本身,它的地址都會被傳遞。
cout << yAdd << endl;
這顯示了 的價值yAdd。不管這個指標是什么,它的值都會被顯示出來。而這個物件的地址, of yAdd,是完全不同的。
void addfun(int **x)
x是這個函式的一個引數。x是一個變數,與程式中的任何其他變數無關。因此,它將有自己的記憶體地址,不同于程式中其他所有內容的記憶體地址(至少在它存在時)。
cout << &x << endl;
這顯示了x的地址。它沒有顯示 的??值yAdd。它也沒有顯示yAdd地址。它顯示了 的地址,這是x該函式的一個引數。
在你的程式中,所有這些都是獨立的、不同的物件和值。
uj5u.com熱心網友回復:
函式內addfun
void addfun(int **x) {
*x = new int[3];
cout << x << endl; // x stores the address of int[0]
// say it is 0x7ffc32e646a0
cout << &x << endl;
}
該宣告
cout << x << endl; // x stores the address of int[0]
// say it is 0x7ffc32e646a0
yAdd列印傳遞給函式的原始指標的地址
addfun(&yAdd);
在這個宣告中
cout << yAdd << endl;
addfun在此陳述句中輸出分配給函式內指標的值
*x = new int[3];
那是動態分配的記憶體的地址。
分配給指標的值yAdd和指標本身的地址是兩個不同的值。
uj5u.com熱心網友回復:
我更改了代碼以列印更多內容并更好地標記它:
#include <iostream>
using namespace std;
void fun(int *x) {
*x = 55;
}
void addfun(int **x) {
cout << endl << "addfun()" << endl;
cout << "x = " << x << endl;
cout << "*x = " << *x << endl;
cout << "new int[3]" << endl;
*x = new int[3];
cout << "x = " << x << endl;
cout << "*x = " << *x << endl;
cout << "addfun() done" << endl << endl;
}
int main()
{
int y = 99;
int *yAdd = &y;
cout << y << endl;
fun(yAdd);
cout << y << endl;
cout << "&yAdd = " << &yAdd << endl;
cout << "yAdd = " << yAdd << endl;
cout << "*yAdd = " << *yAdd << endl;
cout << "address of y is " << &y << endl;
addfun(&yAdd); // so I update the address stored in yAdd to be the same address
// as stored inside the x in the addfun function
cout << "&yAdd = " << &yAdd << endl;
cout << "yAdd = " << yAdd << endl;
cout << "*yAdd = " << *yAdd << endl;
return 0;
}
例如,這會產生以下輸出:
99
55
&yAdd = 0x7ffc9e47fe58
yAdd = 0x7ffc9e47fe54
*yAdd = 55
address of y is 0x7ffc9e47fe54
addfun()
x = 0x7ffc9e47fe58
*x = 0x7ffc9e47fe54
new int[3]
x = 0x7ffc9e47fe58
*x = 0x564ab462d2c0
addfun() done
&yAdd = 0x7ffc9e47fe58
yAdd = 0x564ab462d2c0
*yAdd = 0
正如您所看到的,當您輸入addfunx 的值時,yAdd它是指向的地址y。然后分配int[3]并將結果分配給*x。那就是你將地址存盤int[3]到 wherex指向的地方,即yAdd. 的值x沒有改變。
呼叫后addfun你可以看到,地址yAdd仍然和原來一樣,x但是yAdd現在指向的地方已經變成了int[3]。
我認為您感到困惑的地方是*x = ...。這會改變事物的x指向而不是x自身。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441477.html
上一篇:檢查數字是否是C 中的序列周期
