【问题标题】:Simple Linked List in CC中的简单链表
【发布时间】:2017-04-05 15:40:28
【问题描述】:

这是一个 C 代码,它创建一个包含三个节点的简单链表。之后一个名为printList的函数会遍历创建的列表并打印每个节点的数据。

    // A simple C program for traversal of a linked list
    #include<stdio.h>
    #include<stdlib.h>

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

    // This function prints contents of linked list starting from
    // the given node
    void printList(struct node *n)
    {
        while (n != NULL)
        {
            printf(" %d ", n->data);
            n = n->next;
        }
    }

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

// allocate 3 nodes in the heap
    head = (struct node*)malloc(sizeof(struct node));
    second = (struct node*)malloc(sizeof(struct node));
    third = (struct node*)malloc(sizeof(struct node));

    head->data = 1; //assign data in first node
    head->next = second; // Link first node with second

    second->data = 2; //assign data to second node
    second->next = third;

    third->data = 3; //assign data to third node
    third->next = NULL;

    printList(head);
    printList(head); //question

    return 0;
}

资源:http://quiz.geeksforgeeks.org/linked-list-set-1-introduction/

我的问题是,由于函数printList 的输入参数是一个节点类型的指针,所以在函数调用之后指针的值似乎发生了变化。换句话说,在调用printList(head) 之后,对我来说指针head 现在必须指向NULL 值是合理的,因此对printList 的第二次调用应该打印一些不相关的值。但是,我显然错了,因为这个程序的输出是 1 2 3 1 2 3。

你能解释一下吗?

【问题讨论】:

  • 请格式化您的代码。
  • 当您将参数传递给函数时,它们会按值传递。这意味着该值被复制,并且该函数仅修改副本。原始变量仍将保持其值。
  • 这已经被问了 100 次了。这个程序的输出是什么:void Foo(bar) {bar = 4;} int main() {int x = 0; Foo(x); printf("%d\n", x);}
  • P.S. -> 不要强制转换内存分配的结果。

标签: c linked-list


【解决方案1】:

C 按值传递参数。这意味着传递给函数的变量的值被复制到函数本地的新变量中。无论你在函数内部如何改变局部变量,它都不会改变传递给函数的变量的值。

换句话说:函数内部的nmain中的head相同。局部变量n 刚刚初始化为与head 相同的值

【讨论】:

    【解决方案2】:

    变量是按值传递的;对于值为指针的变量也是如此:

    假设struct node* 类型的变量head 指向一个节点,假设地址为0x12345 的一个节点。 当你调用printList(head),而这个函数的签名是void printList(struct node *n),那么headvalue被复制到nvalue;因此,变量n 和变量head 虽然是不同的变量,但将具有值0x12345。如果printList 则更改n 的值,例如通过语句n = n-&gt;next,则只改变变量n的值;变量head 的值仍然是0x12345

    希望这会有所帮助...

    【讨论】:

    • 非常感谢,你让我明白了。现在我明白了为什么我这么愚蠢并且没有早点做到这一点。
    猜你喜欢
    • 2014-04-04
    • 2010-11-08
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2011-09-17
    相关资源
    最近更新 更多