Note that there are some explanatory texts on larger screens.

plurals
  1. POc - creating a linked list without malloc
    text
    copied!<p>in order to create a linked list(which will contain an attribute of next and previous node),i will be using pointers for the 2 next and previous nodes,yet i was wondering if i could complete the code without using malloc(allocating memory): for example: instead of malloc-ing:</p> <pre><code>link *const l = (link *)malloc(sizeof(link)); if(l == NULL) /* Handle allocation failure. */ ... l-&gt;data = d; l-&gt;next = list-&gt;head; head = l; </code></pre> <p>can i simply create a new link variable with the attributes formatted(value,pointer to next and previous link),and simply link the last link in my last link in the chain to this one? my list file is b,for example.</p> <pre><code>link i; i.date=d; getlast(b).next=&amp;i </code></pre> <p>i appologize ahead for the fact i am new to c,and will be more than glad to receive an honest solution :D</p> <p>edit: i tried using malloc to solve the matter.i will be glad if anyone could sort out my error in the code,as i can not seem to find it.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;malloc.h&gt; struct Node{ int value; struct Node * Next; struct Node * Previous; }; typedef struct Node Node; struct List{ int Count; int Total; Node * First; Node * Last; }; typedef struct List List; List Create(); void Add(List a,int value); void Remove(List a,Node * b); List Create() { List a; a.Count=0; return a; } void Add(List a,int value) { Node * b = (Node *)malloc(sizeof(Node)); if(b==NULL) printf("Memory allocation error \n"); b-&gt;value=value; if(a.Count==0) { b-&gt;Next=NULL; b-&gt;Previous=NULL; a.First=b; } else { b-&gt;Next=NULL; b-&gt;Previous=a.Last; a.Last-&gt;Next=b; } ++a.Count; a.Total+=value; a.Last=b; } void Remove(List a,Node * b) { if(a.Count&gt;1) { if(a.Last==b) { b-&gt;Previous-&gt;Next=NULL; } else { b-&gt;Previous-&gt;Next=b-&gt;Next; b-&gt;Next-&gt;Previous=b-&gt;Previous; } } free(b); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload