-
Link List problem
I need help with a link list, the datastructure receives each struct into the list, but loses the previous one when going through the loop. The first two result print was to check if the list did contain both structs when coming out from the function....
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char * Line;
struct node *next;
}New_prototype;
New_prototype ** Insert_head(New_prototype **head)
{
New_prototype * Current, *tempt;
Current = (New_prototype *)malloc(sizeof(New_prototype));
printf(" Enter a string below\n");
scanf("%s",Current->Line);
Current->next = NULL;
if(*head == NULL)
*head = Current;
else
{
tempt = *head;
while( tempt->next != NULL)
{tempt = tempt->next;}
tempt->next = Current;
}
free(Current);
return(head);
}
int main(void)
{
New_prototype * Head = NULL;
Insert_head(&Head);
printf(" Here is the result is %s \n",Head->Line);
Insert_head(&Head);
printf(" the next result is %s \n",Head->Line);
int i = 0;
while(Head != NULL)
{
char * sentence;
sentence = Head->Line;
printf(" Here is the result %s \n",sentence);
Head = Head->next;
getchar();
}
return(0);
}
-
You aren't ever doing anything with your return value from your insertion function. You should either not bother returning anything, or you should use your return value. Also, you don't actually need to check for that NULL either.
Code:
void insert( struct node **list )
{
if( list )
{
struct node *n = malloc( sizeof( *n ) );
...fill it...
n->next = *list;
*list = n;
}
}
Quzah.
-
well you right about making it a void instead of the return, but what happens at compile time is the same result which it spits out the last thing entered in the list, but the rest is garbage..either way I'm getting the same result...wait nvm