gpt4 book ai didi

c - C 中的简单链表

转载 作者:太空宇宙 更新时间:2023-11-04 06:56:52 24 4
gpt4 key购买 nike

这是一个 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。

你能解释一下吗?

最佳答案

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

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

相同的值

关于c - C 中的简单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43235810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com