用C链表没有的malloc [英] Linked Lists in C without malloc

查看:365
本文介绍了用C链表没有的malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>

typedef struct node
{
      int i;
      struct node *next;
}node;

node getnode(int a)
{
      struct node n;
      n.i=a;
      n.next=NULL;
      return n;
}

main()
{
     int i;
     node newtemp,root,temp;

     scanf("%d",&i);
     root=getnode(i);
     temp=root;

     while(i--)
     {
         newtemp=getnode(i);

         temp.next=&newtemp;
         if(root.next==NULL)
         {
            root=temp;
         }
        temp=*(temp.next);
     }


     temp=root;

     while( temp.next != NULL )
     {
         printf(" %d ",temp.i);
         temp=*(temp.next);
     }
}

我想不使用malloc创建链接列表。编程是只打印的根源,它后面没有节点。我couldn`t发现的bug。曾经有过的内存问题,gcc编译器会抛出一个分段错误。(?)请忽略穷人的编程风格。

I am trying to create a linked-list without using malloc. The programming is printing only the root and no nodes following it. I couldn`t find the bug. Had there been any memory issue, the gcc compiler would have thrown a segmentation fault.(?) Please ignore the poor programming style..

推荐答案

在初始化 temp.next ,什么是您分配给它的指针的值?

When you initialise temp.next, what is the value of the pointer that you assign to it?

temp.next=&newtemp;

为什么,这是同一个每一次! (如果你是不服气画一张。)

Why, it's the same one every time! (Draw a picture if you are unconvinced.)

放弃。如果你需要的内存(其中,与节点数量不确定的,你做的)一个不确定的量,那么你需要分配内存。

Give it up. If you need an indeterminate amount of memory (which, with an indeterminate number of nodes, you do), then you need to allocate memory.

这篇关于用C链表没有的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆