c - 链表追加中指针的指针

标签 c list pointers

我通常用 python 编程。为了提高我的模拟性能,我正在学习 C。在将追加函数实现到链表时,我无法理解指针的指针的使用。这是我的书(Kanetkar 的 Understanding Pointers in C)中的代码摘录。

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

struct node{
    int data;
    struct node *link;
};

int main(){
    struct node *p; //pointer to node structure
    p = NULL;   //linked list is empty

    append( &p,1);
    return 0;
}

append( struct node **q, int num){
    struct node *temp, *r;  //two pointers to struct node
    temp = *q;

    if(*q == NULL){
        temp = malloc(sizeof(struct node));
        temp -> data = num;
        temp -> link = NULL;
        *q = temp;
    }
    else{
        temp = *q;
        while( temp -> link != NULL)
            temp = temp -> link;
        r = malloc(sizeof(struct node));
        r -> data = num;
        r -> link = NULL;
        temp -> link = r;
    }
}

在这段代码中,我将双指针 **q 传递给附加函数。我知道这是地址的地址,即在这种情况下为 NULL 的地址。

我只是不明白为什么有人会这样做。从 append() 函数中的所有内容中删除一个 * 运算符并简单地将 NULL 地址(即 p 而不是 &p)传递给 append() 函数是否无效?

我用谷歌搜索了这个问题。答案要么太难理解(因为我只是一个 C 初学者)要么太简单。感谢您提供任何提示、评论或链接,以便我阅读相关信息。

最佳答案

当您将东西传递给 C 中的函数时,无论是它的变量还是指针,它都是原件的副本。

简单示例:

#include <stdio.h>
void change(char *in)
{
    // in here is just a copy of the original pointer.
    // In other words: It's a pointer pointing to "A" in our main case 
    in = "B";
    // We made our local copy point to something else, but did _not_ change what the original pointer points to.
}
void really_change(char **in)
{
    // We get a pointer-to-a-pointer copy. This one can give us the address to the original pointer.
    // We now know where the original pointer is, we can make _that one_ point to something else.
    *in = "B";
}
int main(int argc, char *argv[])
{
    char *a = "A";
    change(a);
    printf("%s\n", a); /* Will print A */
    really_change(&a);
    printf("%s\n", a); /* Will print B */
    return 0;
}

因此,对 change() 的第一个函数调用会传递一个指向地址的指针副本。当我们执行 in = "B" 时,我们只会更改 我们传递的指针的副本。

在第二个函数调用 really_change() 中,我们获得了一个指向指针的副本。这个指针包含我们原始指针的地址,瞧,我们现在可以引用原始指针并更改原始指针应指向的内容。

希望它能更多地解释它:)

关于c - 链表追加中指针的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15244429/

相关文章:

python - str(list) 如何工作?

WPF 数据网格选择问题

c - 通过指针传递二维数组

c++ - 初学者 C++ - 解释类定义

c - 如何在终端中用c语言打印一组随机字母?

在 clang 中编译而不是 gcc?

c - ESP8266 NonOS 无法连接到其他 ESP8266 托管的 WiFi 网络

python - 移动列表中的元素 (Python)

c - 嵌套类字符串结构中的嵌入与指针

c - gcc 中 -g 选项的作用是什么