Note that there are some explanatory texts on larger screens.

plurals
  1. POSingle linked list in C
    text
    copied!<p>I am trying to write a singly-linked list in C. So far, I just get <strong>segmentation faults</strong>. I am probably setting the pointers wrong, but I just couldn't figure how to do it correctly.</p> <p>The list should be used for "processors" sorted from highest priority (at the beginning of the list) to lowest priority (at the end of the list). Head should point to the first element, but somehow I am doing it wrong.</p> <p>First of all here is the code:</p> <pre><code>struct process { int id; int priority; struct process *next; } struct process *head = NULL; void insert(int id, int priority) { struct process * element = (struct process *) malloc(sizeof(struct process)); element-&gt;id = id; element-&gt;priority = priority; while(head-&gt;next-&gt;priority &gt;= priority) head = head-&gt;next; element-&gt;next = head-&gt;next; head-&gt;next = element; // I put here a printf to result, which leads to segmenatition fault // printf("%d %d\n", element-&gt;id, element-&gt;priority); } /* This function should return and remove element with the highest priority */ int pop() { struct process * element = head-&gt;next; if(element == NULL) return -1; head-&gt;next = element-&gt;next; free(element); return element-&gt;id; } /* This function should remove a element with a given id */ void popId(int id) { struct process *ptr = head; struct process *tmp = NULL; while(prt != NULL) { if(ptr-&gt;id == id) { ptr-&gt;next = ptr-&gt;next-&gt;next; tmp = ptr-&gt;next; } else { prt = ptr-&gt;next; } } free(tmp); } </code></pre> <p>Unfortunately, I could not try out <code>pop()</code> and <code>popId()</code> due to the segmentation fault.</p> <p>May anyone tell me <em>what I am doing wrong?</em></p> <p>EDIT: Now, I edited the insert function. It looks like this:</p> <pre><code>void insert(int id, int priority) { struct process * element = (struct process *) malloc(sizeof(struct process)); struct process * temp = head; element-&gt;id = id; element-&gt;priority = priority; if(head == NULL) { head = element; // edited due to Dukeling element-&gt;next = NULL; } else { while(temp-&gt;next != NULL &amp;&amp; temp-&gt;next-&gt;priority &gt;= priority) temp = temp-&gt;next; element-&gt;next = head-&gt;next; head-&gt;next = element; } // I put here a printf to result, which leads to segmenatition fault // printf("%d %d\n", element-&gt;id, element-&gt;priority); } </code></pre> <p>But I still get segmentation fault for pop() and popId(). What did I miss here?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload