【发布时间】:2022-11-18 10:51:38
【问题描述】:
我试图在 c 中打印单链表的值,但它在打印输入的值后打印垃圾值。我已经编写了使用 do-while 循环创建链表的 create 函数,以及打印链表的 display 函数。我的问题是为什么它在输入值后打印垃圾值。 请帮我找出我的代码哪里做错了,以帮助进一步提高我的编码实践。
试过的代码:
#include <stdio.h>
#include <stdlib.h>
//Declaring the struct variable
struct Node
{
int data;
struct Node *link;
}*head=NULL;
//Creating the Linked List
void create()
{
char ch= 'y';
do
{
printf("ch : %c",ch);
struct Node *p,*q;
p = (struct Node*)malloc(sizeof(struct Node*));
printf("\nEnter the Data : \n");
scanf("%d", &p->data);
p->link = NULL;
if(head == NULL)
{
head = p;
}
else
{
q->link = p;
}
q=p;
scanf("%c",&ch);
}while(ch!= 'n');
}
//Displaying the Linked List
void display()
{
struct Node *p=head;
if(p == NULL)
{
printf("\n List is Empty \n");
}
else
{
while(p!=NULL)
{
printf("%d -->", p->data);
p = p->link;
}
}
}
int main()
{
printf("\n Enter the data into the linked list: \n");
create();
printf("\nCreation Complete........ Displaying\n");
display();
return 0;
}
输出:
1
2
3
4
5
6
n
Creation Complete........ Displaying
1 --> 2 --> 3 --> 4 --> 5 --> 6 -->7097656 -->
【问题讨论】:
-
sizeof(struct Node*)是指向节点的指针的大小。你想分配一个节点。去掉星星。当你这样做时,删除malloc的返回值的转换。它没有任何帮助,在某些情况下可以隐藏错误。
标签: c