#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);
}
}
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..
An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used for storing similar types of elements as the data type must be the same for all elements.
Another way to create a generic linked list is to use macros. There are several implementations of these types of linked lists (and other data structures) floating around on the internet, which provide a generic implementation of a linked list without the need for dynamically allocating data.
Actually you can use free without calling malloc , but only if the value you pass to free is a null pointer. So not useful if what you want is a pointer which might point to an allocated block, but might point to a local array.
It allocates the required memory to the compiler at runtime to use and program works well.
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.
You can avoid malloc but not for free:
You only have two memory spaces that you can use to store nodes, and those are root
and newtemp
. When you assign a new node to newtemp
the old node doesn't exist anymore.
Assuming you entered the number 5
at the scanf, before first iteration of the loop, you have:
5 -> NULL
After the first iteration of the loop, you have
5 -> 4 -> NULL
After the second iteration of the loop, you have
5 -> 3 -> NULL
(The node containing 4
has been completely replaced by the node containing 3
).
The only solution is to use malloc
, and make getnode
return a node*
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With