为指针指定另一个指针的地址

时间:2013-10-03 23:34:37

标签: c pointers

我对以下代码的含义感到非常困惑。在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);
}

2 个答案:

答案 0 :(得分: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 :(得分: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;
}
相关问题