我正在通过书本学习链接列表,在一个书本中,头指针是全局初始化的,在另一个书本中,指针是在主体中初始化的,然后传递给创建。在main中声明它有什么好处。

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

最佳答案

c中的内存模型如下

Global variables go into `BSS (Block start with Symbols) region`

Global initialized variables go into `Initialized data region`

Scope limited variables go into `Stack`


默认情况下,在main中声明的变量具有存储分类器automatic
因此,它们都进入stack。但是,如果您在main(或任何地方)中有static variables,它们将进入'BSS'。

因此,这有所作为。 main中的大量数据需要large stack

07-28 02:02
查看更多