【发布时间】: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