Reputation: 1522
I have, for a large portion of the day, been trying to write a simple program with linked lists. My main issue seems to be not understanding why the memory I am accessing is not what I think it is. I am printf crazy and outputting every possible form of data I can and still am having trouble understanding why it will not work.
For example when I pass the &head
to a function which takes node **location
and I want to check whether the value inside location
(and therefore head
) is NULL
or not, should I use if(!*location) return;
or should I use if(!location) return;
, It seems the later is correct, but why?
And when I want to create a node *current
inside a function to keep track of things, should I start with node* current = *head
or node* current = head
, and most importantly, why? I have noticed that the later is better, but I cannot make sense of it still. Warnings go away when I typecast the statements, but it seems to fix nothing.
Here is some functions I have been writing, can you please give me hints on where I am not making sense in the code. Preferably, I hope to understand why the output seems to be a memory location and then accessing bad memory.
#include <stdio.h>
#include <stdlib.h>
typedef struct node_struct
{
int val;
struct node *next;
} node;
node* return_create_neck(node **head, int value)
{
node* ptr;
*head = ptr = (node *)malloc(sizeof(node));
(*head)->val = value;
(*head)->next = NULL;
return ptr;
}
node* return_append_tail(node **location, int value)
{
node* ptr;
*location = ptr = (node *)malloc(sizeof(node));
(*location)->val = value;
(*location)->next = NULL;
return ptr;
}
void print_linked_list(node **head)
{
if(!head)
return;
node *current = head;
while(current)
{
printf("%d ", current->val);
current = current->next;
}
printf("\n");
return;
}
int main(void)
{
node *head=NULL, *current=NULL;
int i=0;
for( current = return_create_neck(&head, 1);
i < 4;
current = return_append_tail(¤t, i+1))
{ ++i; }
printf("Pritning...\n");
print_linked_list(&head);
return 0;
}
Upvotes: 0
Views: 2355
Reputation: 409166
Your return_append_tail
function doesn't actually append anything, unless called with the correct location
, which you do not.
You should call it with ¤t->next
from the main
function.
Upvotes: 2