【问题标题】:creating link list without pointer vs with pointers创建没有指针的链接列表与使用指针
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 谢谢,但在另一个网站上找到了我想要的东西:geeksforgeeks.org/…
  • 因此,如果您发布您发现的内容,那将对搜索中的某个人有帮助,恕我直言
猜你喜欢
  • 2013-08-26
  • 1970-01-01
  • 2020-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多