Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 为指针分配另一个指针的地址_C_Pointers - Fatal编程技术网

C 为指针分配另一个指针的地址

C 为指针分配另一个指针的地址,c,pointers,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));

我很困惑下面的代码是什么意思。在
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);
}

当您通过指针传递时,您希望函数内所做的更改对调用方可见:

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);

可能这段经过修改和注释的代码会帮助您理解

// 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;
}

您确定它不是
void somefunction(结构节点**B)
?(有两个“*”)我也是这么想的,但显然不是。我再次检查了我教授发布的代码,它只是*B。那一行,*B真让我困惑。如果是**B,那么对我来说是有意义的。也许你的教授没有他应有的聪明\如果不是
**
,请打开编译器警告,并在警告上添加中止标志(例如
-Wall-Werror
)。只有在编译器非常宽松的情况下,该代码才会编译。