将一个双指针传递给一个函数,并为它指定一个函数本地指针的地址

问题描述:

下面是一些将双指针传入函数的代码。双指针然后被分配在函数中创建的指针的地址。当我打印出存储在双指针中的地址时,它会打印NULL,这是我在将它传递给函数之前最初给出双指针的值。将一个双指针传递给一个函数,并为它指定一个函数本地指针的地址

#include <stdio.h> 
#include <stdlib.h> 

struct node 
{ 
    int value; 
}; 

void append(struct node **nodePtr); 

int main() 
{ 
    struct node **nodePtr = NULL; 

    append(nodePtr); 
    printf("\nnodePtr = %p", nodePtr); 

    return 0; 
} 

void append(struct node **nodePtr) 
{ 
    // creating new node 
    struct node *currentNode = malloc(sizeof(struct node)); 

    // assigning the address of currentNode to the double pointer NodePtr 
    nodePtr = &currentNode; 

    printf("\n&currentNode = %p", &currentNode); 
} 

This is the result I get when I run the code

我知道,如果你传递一个指针到它通过引用传递的功能,这意味着您对在函数指针的任何变化,当你外部访问指针不会消失功能。

我的问题是,为什么我不能访问函数外的currentNode的地址。我把它分配给一个双指针,所以我应该能够访问它的功能?对?

上面已经被回答

谢谢您的回答保罗,它的工作完美。我试图扩展到代码。我想将nodePtr分配给名为头部的结构指针。当我调用函数时,我想将currentNode中的地址存储到头指针中。

最初我以为改变下面显示的函数内部的代码将工作。

*nodePtr = currentNode; 

但这不起作用,因为我只是改变nodePtr中的内容而不是head中的内容。

然后我试着将nodePtr初始化为head的地址。

struct node *nodePtr = &head; 

但这不起作用,因为它不是一个双指针。如果我将它初始化为一个双指针,我就遇到了我之前做过的同样的问题。下面

是我的代码到目前为止

#include <stdio.h> 
#include <stdlib.h> 

struct node 
{ 
    int value; 
}; 

void append(struct node **nodePtr); 

int main() 
{ 
    struct node *head = NULL; 
    struct node *nodePtr = head; 

    append(&nodePtr); 

    printf("%p", head); 
    return 0; 
} 

void append(struct node **nodePtr) 
{ 
    // creating new node 
    struct node *currentNode = malloc(sizeof(struct node)); 

    // assigning the address of currentNode to the double pointer NodePtr 
    *nodePtr = currentNode; 
} 
+0

没有“双指针”这样的东西。只有指针。指针可以指向任何东西,包括指针。指向指针的指针仍然只是指针,而不是“双指针”。如果你牢记这一点,很多混乱应该消失。 – gnasher729

你的主要应该是:

int main() 
{ 
    struct node *nodePtr = NULL; 

    append(&nodePtr); 
    printf("\nnodePtr = %p", nodePtr); 

    return 0; 
} 

所以,如果你主要通过NODEPTR的地址

在追加,则必须立即取消引用该指针:

// assigning the newly allocated currentNode to the double pointer NodePtr 
    *nodePtr = currentNode; 

(所以不要asssign局部变量currentNode的地址,因为本地变量将停止在函数返回之后存在您分配。指针由malloc返回。)

我建议你使用笔和纸画的mainappend内存和绘制指针,看看发生了什么,什么都存储在哪里。

如果你坚持使用双指针,你需要在函数中传递一个三元指针。

在您的代码中,更改是在函数内部执行的,但是它们在终止后不会保留。

但是,您并不需要在您的main()中使用双指针,只需使用一个指针,然后按原样保留函数。