2013-10-03 49 views
0

我非常困惑以下代碼的含義。在somefunction該參數是一個指向結構節點的指針。在我主要的參數中是另一個指針A的地址位置。那麼這究竟意味着什麼呢? A和B有什麼區別? A和B代表相同的指針嗎?現在B在(*B)=C之後是否指向C?指定另一個指針的地址指針

struct node{ 
    int value; 
}; 

void somefunction(Struct node *B) 
{ 
    struct node *C = (struct node *)malloc(sizeof(struct node)); 
    (*B)=C; 
}; 

main() 
{ 
    struct node *A; 
    somefunction(&A); 
} 
+0

你確定它不是'void somefunction(struct node ** B)'? (有兩個'*') –

+0

這就是我的想法,但顯然不是。我查看了我的教授再次發佈的代碼,它只是* B。那一行,* B真讓我困惑。如果它是** B那麼它對我來說是有意義的。 – user68212

+0

也許你的教授並不聰明,他應該是..:\ – goji

回答

1

當你路過的指針,你想在一個函數中所做的更改是給調用者可見:

struct node { 
    int value; 
}; 

void foo(struct node* n) { 
    n->value = 7; 
} 

struct node n; 
foo(&n); 
// n.value is 7 here 

,當你想改變指針本身你傳遞一個指針的地址:

void createNode(struct node** n) { 
    *n = malloc(sizeof(struct node)); 
} 

struct node* nodePtr; 
foo(&nodePtr); 
1

可能是這個修改和註釋的代碼將幫助你理解。

// Step-3 
// Catching address so we need pointer but we are passing address of pointer so we need 
// variable which can store address of pointer type variable. 
// So in this case we are using struct node ** 
//now B contains value_in_B : 1024 
void somefunction(struct node **B) 
{ 
    // Step-4 
    // Assuming malloc returns 6024 
    // assume address_of_C : 4048 
    // and value_in_C : 6024 //return by malloc 
    struct node *C = (struct node *)malloc(sizeof(struct node)); 

    // Step-5 
    // now we want to store value return by malloc, in 'A' ie at address 1024. 
    // So we have the address of A ie 1024 stored in 'B' now using dereference we can store value 6024 at that address 
    (*B)=C; 
}; 

int main() 
{ 
    // Step-1 
    // assume address_of_A : 1024 
    // and value_in_A : NULL 
    struct node *A = NULL; 

    // Step-2 
    // Passing 1024 ie address 
    somefunction(&A); 

    // After execution of above stepv value_in_A : 6024 
    return 0; 
}