-
...if I only Node...
[code]
typedef struct Supreme
Supreme *head;
Supreme *prev;
char *stringData;
Supreme *next;
Supreme *tail;
CreateAddSupremeNode (Supreme *head)
Supreme s = (Supreme *)malloc (sizeof(Supreme));
if(head == NULL)
{ head = s;
return s; }
Supreme x;
for(x = head; x != NULL; x = x->next)
;
x->next = s;
return s;
???This Crashes My System....
-
Code:
Supreme *CreateAddSupremeNode( Supreme **head )
{
Supreme s = malloc( sizeof( Supreme ) );
if (*head == NULL)
{
*head = s;
}
else
{
Supreme x;
for( x=*head; x && x->next; x = x->next );
x->next = s;
}
return s;
}
In both cases you were trying to use null pointers. If head was null, you cannot assign it the value of s. This:
if( node->next == NULL ) node->next = s;
Is not the same as:
if( head == NULL ) head = s;
The second problem was that your loop would make sure that 'x' was null, then you'd try assigning 'x->next' a value, and since 'x' was already null, BadThings(TM) happened.
Quzah.
-
Ok but why **head?
Won't *head work?
-
Consider a call to CreateAddSupremeNode...
Code:
int main ()
{
Supreme * head = NULL; // The list is empty.
CreateAddSupremeNode (head); // This is bad...
// Now the list is not empty, so the value of head is not NULL.
// BUT that means changing the value of a passed variable,
// and the only way to do that is to pass a reference to the
// variable, which would be...
CreateAddSupremeNode (&head); // This is correct way to
// change value of head.
return 0;
}
So, since head is a Supreme *, &head is gonna be a Supreme **, and instead of changing the value of head in your function, you'll have to change the value of *head.
-