C语言链表动态存储数据实现:仅输出单个值的问题如何解决?
错误原因
- 你通过
malloc一次性申请了n个连续的struct node内存空间后,没有初始化每个节点的next指针,第一个节点的next是未定义的野指针,执行第一次temp = temp->next后temp就变成了非法地址,循环直接终止,因此仅能存储、打印第一个节点的值。 - 你的写法本质是用连续数组模拟链表,不符合常规链表链式存储的实现逻辑,但如果要保留你当前的分配方式,只要补全
next指针的初始化即可。
修复后可运行代码
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; // 打印链表 void printList(struct node *ptr) { int i = 1; while(ptr != NULL) { printf("\n Value in Node %d : %d",i ,ptr->data); ptr = ptr->next; i++; } } int main() { int n; struct node *head; struct node *temp; printf("\n Enter the size of linkedList : "); scanf("%d",&n); head = malloc(sizeof(struct node) * n); if(head == NULL){ printf("内存分配失败"); return 1; } // 初始化所有节点的next指针 for(int j=0;j<n;j++){ if(j < n-1){ head[j].next = &head[j+1]; }else{ head[j].next = NULL; } } // 将head赋值给temp temp = head; int i = 1; // 记录链表节点位置 while(temp != NULL) // 遍历到链表末尾 { printf("\n Enter the value in node %d : ", i); scanf("%d",&temp->data); temp = temp->next; // 赋值下一个节点地址 i++; } printList(head); // 释放申请的内存 free(head); return 0; }
补充说明
如果要实现标准的非连续存储链表,应该每创建一个节点就单独调用一次malloc分配内存,而不是一次性分配连续的数组空间,这种实现方式支持后续动态增删节点,灵活性更高。
内容的提问来源于stack exchange,提问作者Nagraju Kasarla
相关产品推荐
相关产品推荐

