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

查看:35
本文介绍了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 的情况下创建一个链表.编程只打印根,没有节点跟随它.我找不到错误.如果有任何内存问题,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天全站免登陆