显示单链表的元素

时间:2012-07-13 14:30:17

标签: c

我编写了一个简单的程序来遍历链表的节点。

struct node
{
    int data;
    struct node *next;
}*start;
start=(struct node *)malloc(sizeof(struct node));
start->next=NULL;

int main(void)
{
    if(start==NULL)
    {
        printf("There are no elements in the list");
    }

    else
    {
        struct node *tmp;
        printf("\nThe elemnets are ");
        for(tmp=start;tmp!=NULL;tmp=tmp->next)
        {
            printf("%d\t",tmp->data);
        }
    }
    return 0;
}

每当我尝试打印链表的元素时,即使列表为空,也会提供输出

The elements are 5640144

我做错了什么?我正确地声明了开始指针吗?

为什么我需要这样做(实际上我最初并没有这样做,但是被我的一个朋友要求)

start=(struct node *)malloc(sizeof(struct node));
start->next=NULL;

2 个答案:

答案 0 :(得分:4)

声明指向节点(start)的指针实际上并不创建节点本身 - 您需要malloc()来执行此操作。但是,malloc()无法用合理的值填充节点,这就是data中看似随机的值的原因。在start->data = 42;后尝试start->next = NULL;

编辑:请参阅ArjunShankar关于不从函数外部调用malloc()的评论。

答案 1 :(得分:1)

目前它可能肯定会给你垃圾价值, 存在于已分配的内存块中,就像你在指定的start-> next = NULL;没有为数据赋值,

请使用带有0的memset,它将为整个结构初始化内存块为零,或者对结构初始化一些值。

如果您使用过gcc,可能不会引发这个问题。我猜你也不会这样。

struct是全局的, start 是一个指向结构的指针,在malloc时, 你已经分配了一个结构大小的内存,初始化。 如果您已经采用了全局结构变量,则不会遇到这样的问题,因为它在 bss 中初始化。

#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
}*start;

int main(void)
{
start=(struct node *)malloc(sizeof(struct node));
start->next = NULL;
start->data = 100;
//memset(start,0,sizeof(struct node));
if(start==NULL)
{
    printf("There are no elements in the list");
}
else
{
    struct node *tmp;
    printf("\nThe elemnets are ");
    for(tmp=start;tmp!=NULL;tmp=tmp->next)
    {
        printf("%d\n",tmp->data);
    }
}
return 0;
}