【问题标题】:Difference between single and double pointers appending [duplicate]附加单指针和双指针的区别[重复]
【发布时间】:2019-04-02 03:38:48
【问题描述】:

这可能是一个愚蠢的问题,但我真的很想知道为什么会这样。当试图为链表创建附加函数时,为什么这个单指针解决方案不起作用,但是当使用双指针时它起作用?

单指针:

void append(node *head, int value){
node *current = head;
node *new = malloc(sizeof(node));
if (new == NULL){
    printf("couldn't allocate memory");
    return;
}
new->value = value;
new->next = NULL;
if (head == NULL){
    head = new;
    return;
}
while (current->next != NULL)
    current = current->next;
current->next = new;
return;}

双指针:

void append(node **head, int value){
node *current = *head;
node *new = malloc(sizeof(node));
if (new == NULL){
    printf("couldn't allocate memory");
    return;}
new->value = value;
new->next = NULL;
if (*head == NULL){
    *head = new;
    return;
}
while (current->next != NULL)
    current = current->next;
current->next = new;
return;}

【问题讨论】:

    标签: c linked-list


    【解决方案1】:

    想象一下,你的脑袋还在记忆中 ------------- ------------ | head 0x10 | -> | 0x20 | ------------- ------------

    0x10是head的地址,不是它指向的地址,它指向的地址是0x20。

    如果你只用一个指针调用append,它会将头值复制到函数append的本地地址 这样,append head 可以是: ------------- ------------ | head 0x25 | -> | 0x20 | ------------- ------------

    所以,head的新地址是0x25,指向0x20

    如果你在函数内部使用head 来指向另一个地址,例如: ------------- ------------ | head 0x25 | -> | 0x30 | ------------- ------------

    只有函数内部的head 将指向不同的地址,在调用函数中它仍然是: ------------- ------------ | head 0x10 | -> | 0x20 | ------------- ------------

    因为您是按值传递指针,所以函数正在制作指针的副本。 要解决这个问题,您需要将指针传递给指针,因此您的变量将是:

    local
    ------------- ------------- ------------ | head 0x25 | -> | head 0x10 | -> | 0x20 | ------------- ------------- ------------

    现在你有了一个指向调用者指针的指针,所以你可以改变它指向的地方,它会反映在调用者头上。

    例如

    local
    ------------- ------------- ------------ | head 0x25 | -> | head 0x10 | -> | 0x30 | ------------- ------------- ------------

    【讨论】:

      【解决方案2】:

      当使用参数调用函数时,会在堆栈上创建该参数的副本。所以在某种程度上,它们与局部变量非常相似。

      在单指针情况下,语句head = new; 实际上只是导致参数head 的更改,并且此更改不会传播回传递的实际头部。

      在双指针情况下,您将获得head 的地址,您可以通过执行*head = new; 来更改该地址。

      【讨论】:

        猜你喜欢
        • 2016-02-03
        • 2021-09-21
        • 2012-11-17
        • 2011-09-22
        • 1970-01-01
        • 2018-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多