我正在迭代一個樹資料結構,它有一個指向其根的指標,如下所示-
struct node *root;
當我必須將此根的參考作為引數傳遞給函式時......我必須像這樣傳遞它-
calcHeight(&root);
-
-
-
//somewhere
int calcHeight(struct node **root) // function defination is this
我的問題是 - 為什么我們需要將“root”指標作為 &root 傳遞?我們不能像這樣傳遞 root--
struct node *root;
calcHeight(root);
int calcHeight(struct node *root);
uj5u.com熱心網友回復:
struct node *是一個指向 a 的指標struct node。
struct node **是一個指向 a 的指標的指標struct node。
傳入 a 的原因struct node **可能是該函式需要修改struct node *實際指向的內容——這對于名為calcHeight. 如果是freeNode這樣,它可能是有道理的。例子:
void freeNode(struct node **headp) {
free(*headp);
*headp = NULL; // make the struct node * passed in point at NULL
}
演示
另一個原因可能是使介面保持一致,以便始終需要為struct node **支持struct nodes 的函式中的所有函式提供 a - 不僅僅是那些實際需要更改struct node *指向的函式。
uj5u.com熱心網友回復:
因為在calcHeight你通過價值傳遞你的論點。如果要修改指向的值,則root需要傳遞指標的地址。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/372819.html
