3

I have written a simple program to traverse through the nodes of a linked list.

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;
}

Whenever i am trying to print the elements of the linked list, however even though the list is empty, it gives the output

The elements are 5640144

What am i doing wrong ? Am i declaring the start pointer correctly ?

Why do i need to do this (actually i was not doing this initially, but was asked to by one of my friends)

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

2 回答 2

4

声明指向节点 ( start) 的指针实际上并不创建节点本身 - 您需malloc()要这样做。但是,malloc()不必费心用合理的值填充节点,这就是为什么你会在data. start->data = 42;之后试试start->next = NULL;

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

于 2012-07-13T14:35:07.230 回答
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;
}
于 2012-07-13T14:45:08.553 回答