【发布时间】:2014-01-31 11:42:18
【问题描述】:
我正在通过书学习链接列表,在一本书中,头指针被全局初始化,在另一本书中,它在 main 中初始化,然后传递给创建。在 main.js 中声明它有什么好处吗?
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
void create(void);
void traverse(void);
void create()
{
char ch;
struct node *ptr,*cpt;
ptr=(struct node*) malloc(sizeof(struct node));
if(ptr==NULL)
{
printf("Memory cant be allocated");
}
printf("Enter information you want to store in node.\n");
scanf("%d",&ptr->info);
first=ptr;
do
{
cpt=(struct node*) malloc(sizeof(struct node));
if (cpt==NULL)
printf("Can't allocate memory");
printf("Enter next node information.");
scanf("%d", &cpt->info);
ptr->link=cpt;
ptr=cpt;
printf("Do you want to enter another node?(y/n)");
ch=getch();
}while(ch=='y');
ptr->link = NULL;
}
【问题讨论】:
-
如果您想在 SO 中发布代码,请正确缩进您的代码。并使用空格而不是制表符。
-
Please don't cast the return value of
malloc()in C。如果您的书在没有详细说明这样做的情况下这样做可能是个坏主意,请考虑阅读其他内容。 -
我认为这个问题与标题不符。
-
@unwind 除非这本书是 K&R,然后忽略演员表和第 6.5 节中关于它是必要的评论。
标签: c pointers linked-list