0

我对以下代码的含义感到非常困惑。参数中somefunction是一个指向结构节点的指针。我要输入的主要参数是另一个名为 A 的指针的地址位置。那么这到底是什么意思呢?A和B有什么区别?A 和 B 代表同一个指针吗?B 现在是否在该行之后指向 C (*B)=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);
}
4

2 回答 2

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);
于 2013-10-03T23:42:48.847 回答
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;
}
于 2013-10-04T08:02:32.453 回答