pointers - 为什么我的函数使用按值调用方法?
问题描述
我不知道为什么在最后一行打印第一个元素的数据而不是最后一个元素。我要解释。
// 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);
printf("%d",head->data);
return 0;
}
由于该函数正在接受指针,因此应该通过引用调用它。当 n 指针等于 NULL 时,在函数的最后一个循环中。但是在这段代码的最后一行是打印我的链表的第一个列表的数据。
解决方案
实际上你正在做的事情并没有在实际的链表中完成,它不是通过引用传递的
void printList(struct Node* n)
{
/* some code here */
}
void main()
{
/* all your code here */
printList(head);
}
因此,如果您想更改实际链表中的头,则必须将指针头的地址传递给类似这样的函数
int append_list(node **head, int data)
{
while((*head)->next!=NULL)
{
(*head) = (*head)->next;
}
}
int main()
{
struct node *head = NULL;
/* add nodes */
print_list(&head);
}
所以这是您的代码中的修改:
#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)->next != 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);
printf("%d",head->data);
return 0;
}
这里的输出将是
1 2 3
由于您已使用 (*head) 进行遍历,因此您不再有权访问您的列表,因此如果您尝试访问,则会出现分段错误
(*head)->next
但我不建议这样做,因为现在您将无法释放内存
推荐阅读
- firebase - “错误:13 内部:发生内部错误”有时发生在 firebase 函数的触发器中
- python - AIOserial 问题:“ImportError:尝试使用没有已知父包的相对导入”
- activemq - 无法创建/run/activemq.pid:权限被拒绝
- javascript - 如果 jQuery 的数据属性为真
- openpyxl - 使用openpy python为excel中的整个列创建一个下拉列表
- visual-studio - Xamarin Prism BindingContext to ViewModel for Intellisense 数据建议
- javascript - 使用 Math.floor 获得毫秒数
- excel - VBA:用户表单组合框(获取运行时 1004:对象“_Worksheet”的方法“范围”)
- sql-server - 删除文件名 MSSQL 的部分字符
- javascript - 如何在ember帮助器中将UTC时间转换为momentjs中的指定格式