【问题标题】:A head node of a linked list is passed to another function where it is assigned to a local node in the function. Why is there no error?链表的头节点被传递给另一个函数,在该函数中它被分配给函数中的本地节点。为什么没有错误?
【发布时间】:2015-10-28 10:01:54
【问题描述】:

“a”是链表的头节点。所有节点的内存都是通过 malloc 分配的。在构建列表 (10 20 30 40) 之后,我将它传递给另一个函数,在该函数中我将它分配给一个在本地声明的节点“当前”并且没有执行 malloc。但是我能够正确遍历整个列表。 “当前”访问的是堆内存中的链表吗?

void main()
{
    struct node* a = (struct node*) malloc (sizeof(struct node));
    struct node* temp = (struct node*) malloc (sizeof(struct node));


    a->data = 10;
    temp->data = 20;
    a->next = temp;

    temp = (struct node*) malloc (sizeof(struct node));
    temp->data =25;


    temp = (struct node*) malloc (sizeof(struct node));
    temp->data = 30;
    a->next->next = temp;


    temp = (struct node*) malloc (sizeof(struct node));
    temp->data = 40;
    a->next->next->next = temp;

    a->next->next->next->next = NULL;

    printlist(a);

}


void printlist(struct node* head)
{
    struct node* current = head;
    while (current != NULL)
    {
        printf("%d ",current->data);
        current = current->next;
    }
}

【问题讨论】:

  • "current是在访问堆内存中的链表吗?"。是的。这就是指针的工作原理。指针存储内存位置的地址。在这种情况下,current 设置为指向与 head 指向的位置相同的位置。

标签: c pointers linked-list heap-memory stack-memory


【解决方案1】:

指针变量的值是它所指向的地址。该值可以复制并分配给其他变量,就像任何其他非指针变量一样。

当您将a 传递给printlist 函数时,指针会复制到局部变量head,然后再复制到current 变量。现在您有三个指针(main 函数中的a,head 和current 函数printlist),都指向同一个位置。

【讨论】:

    【解决方案2】:

    这很简单,current 是一个指针,你把存储在'a'中的任何东西都给了它,它是一个头节点的地址。在本地声明 current 并不重要,当然您不需要使用 malloc,因为您没有创建新节点。变量 current 本身将在您离开该功能时被释放。用代码解释一下:

    void printlist(struct node* head)
    {
        printf("%p\n", head); //head has the memory address of first node
        struct node* current = head; //you created a pointer (struct node pointer) 
        //and gave it the address of the first node (you didn't create a new node
        //so there is no need for malloc)
        //size of current is size of a pointer and not a struct node
        printf("current: %p\n", current); //this will print that same address
        // which is first node address 
        while (current != NULL)
        {
            printf("%d ",current->data);
            //notice you're not using 'current.next' which would have been 
            //the case if current was local node. instead you're accessing head.
            current = current->next; 
        }
    }
    

    【讨论】:

      【解决方案3】:

      指针基本上是存储变量值的内存地址。

      无论你从哪个函数使用它,如果变量还在堆中,就可以通过那个地址访问它。

      由于您的节点还使用指针(即地址)引用列表的其他元素,因此无论您从何处访问它,您都会获得整个列表。

      【讨论】:

        【解决方案4】:

        您正在传递一个指针,该指针是指向链接列表头部的地址。在函数内部,您将当前节点分配给头指针,它是堆中的一个位置。因此,您可以遍历它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-03-28
          • 2011-07-19
          • 2010-12-15
          • 2016-08-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多