c - creating a linked list without malloc
c, malloc
Solution
Not really.
You could create a variable for each and every node in your list, but what happens when you want another node? Fifty more nodes? These variables also won't hang around after you've left the scope they were defined in, which means you'd either have to make everything global or use static storage and expose a pointer to them. This means that all pointers to them after that scope will be invalid. These are both very ugly solutions.
If you don't understand what I mean by scope, here's a quick example:
int main() { /* Entering function scope. */
int x = 5;
{ /* Entering block scope. */
int y = 7;
printf("%d\n", y);
} /* Exiting block scope, all variables of this scope are gone. (y) */
printf("%d %d\n", x, y); /* Won't compile because y doesn't exist here. */
} /* Exiting function scope, all non-static storage variables are gone. (x)
You could also create a global array, thinking that this gets around having a lot of different variables, but if your solution is to implement this using an array, why are you using a linked list and not an array? You've lost the benefits of a linked list by this point.
Problem
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: ``` link *const l = (link *)malloc(sizeof(link)); if(l == NULL) /* Handle allocation failure. */ ... l->data = d; l->next = list->head; head = l; ``` 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. ``` link i; i.date=d; getlast(b).next=&i ``` i appologize ahead for the fact i am new to c,and will be more than glad to receive an honest solution :D 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. ``` #include <stdio.h> #include <malloc.h> 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->value=value; if(a.Count==0) { b->Next=NULL; b->Previous=NULL; a.First=b; } else { b->Next=NULL; b->Previous=a.Last; a.Last->Next=b; } ++a.Count; a.Total+=value; a.Last=b; } void Remove(List a,Node * b) { if(a.Count>1) { if(a.Last==b) { b->Previous->Next=NULL; } else { b->Previous->Next=b->Next; b->Next->Previous=b->Previous; } } free(b); } ```