【问题标题】:Getting garbage values when printing the linked list in c在c中打印链表时获取垃圾值
【发布时间】: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


【解决方案1】:

以下是 64 位 Windows 主机上的示例:

测试.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Node
{
  int data;
  struct Node *link;
}*head=NULL;

int main(int argc, char* argv[])
{

  printf ("sizeof(struct Node): %lld, sizeof(struct Node*): %lld
",
    sizeof(struct Node), sizeof(struct Node*));
  return 0;
}

输出:

sizeof(struct Node): 16, sizeof(struct Node*): 8

换句话说,你可能想要malloc(sizeof(struct Node)

【讨论】:

    猜你喜欢
    • 2020-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2017-10-28
    • 2015-08-05
    • 1970-01-01
    • 2016-12-07
    相关资源
    最近更新 更多