I'm "translating" this program from a pseudo Pascal language. Recently I learned C structs and pointers features, and from the start I noticed that pointers are very annoying. So this is a recursive version of the Sorted Insertion in a Linked List algorithm, and it still gives me problems, like crashing.
typedef struct node Node;
struct node
{
int info;
struct node *link;
};
void ordered_insert_rec(Node *head, Node *new_node)
{
if(!head)
{
new_node->link = head;
head = new_node;
}
if(new_node->info < head->info)
{
new_node->link = head;
head = new_node;
}
else
{
ordered_insert_rec(head->link, new_node);
}
This is the main:
int main()
{
Node head;
Node node;
Node node2;
Node inserting_node;
head.info = 1;
head.link = &node;
node.info = 3;
node.link = &node2;
node2.info = 7;
inserting_node.info = 5;
ordered_insert_rec(&head, &inserting_node);
Node *front = &head;
while(front)
{
printf("%d ", front->info);
front = front->link;
if(!front)
{
exit(1);
}
}
}
Maybe I'm doing something wrong with the list printing at the end of the algorithm, is it? In the prompt the output is "1 3 7" but the program crashes after a while. It must be "1 3 5 7", by this way I noticed up that the procedure "ordered_insert_rec" doesn't work correctly.
Thanks for the help. :)
node2.link=0;to your code too. you crash because you are accessing invalid address.order_insert_reclogic should beif()...else if()....else. Just check what happens now!node2.linkandinserting_node.linkare not initialized: undefined behavior.