linked list - Move value to end of queue in C -


i'm new c , i'm trying use function move value end of queue. works first 2 times, third time goes wrong regarding while loop , i'm not sure what's causing it. @ appreciated. :)

void enqueue(queue q, int value) {     if (q == null)     {         return;     }      // create new node     node * newnode = (node *)malloc(sizeof(node));      if (newnode == null)     {         return;     }      // add node end of queue     newnode->value = value;      if (q->head == null)     {         newnode->next = q->head;         q->head = newnode;     }     else     {         node * head = q->head;          while (head->next != null)         {             head = head->next;         }          // update queue pointer         head->next = newnode;     } } 

if q->head non-null, never set newnode->next, leaving uninitialised. next code walk list follow uninitialised pointer, leading undefined behaviour , crash.

to fix this, need initialise newnode->next

newnode->value = value; newnode->next = null; if (q->head == null) {     q->head = newnode; } else     /* code before */ 

Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -