Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You must first of all initialize head pointers:</p> <pre><code>head = (node *)malloc(sizeof(node)); head-&gt;prev = NULL; head-&gt;next = NULL; </code></pre> <p>To read the file I'd suggest using fgets():</p> <pre><code>p = fopen("studentRecords.txt","r"); while(!feof(p)) { fgets(head-&gt;data, 50, p); </code></pre> <p>Usually you allocate a somewhat larger buffer (say 1K, memory is usually cheap), read a line into the buffer and check that it is valid and a suitable length. If it is not, you can issue an informative error ("Line XXX, the value 'yyy' is too long") and abort, or ignore the line and go on. You can also use strdup() to avoid the issue altogether, using a structure with *data instead of data[50]. You might actually end up SAVING memory that way.</p> <p>Using fgets with a shorter buffer might result in a 52-characters line being read as two faulty records without any warning.</p> <p>Finally here the code is too compact - and you again do not initialize pointers:</p> <pre><code> head-&gt;next = (node *)malloc(sizeof(node)); head-&gt;next-&gt;prev = NULL; head-&gt;next-&gt;next = NULL; </code></pre> <p>What you ought to do, once you have your line in a temp buffer, is to create a new node, fully initialize it, and then place it as the new head:</p> <pre><code> newNode = (node *)malloc(sizeof(node)); newNode-&gt;prev = NULL; newNode-&gt;next = head; head-&gt;prev = newNode; // A strncpy(head-&gt;data, temp, 50); head-&gt;data[49] = 0x0; // B // head-&gt;data = strdup(temp); head = newNode; </code></pre> <p>The all-on-one-line head->next = (node*)... may look nifty, but it tends to quickly become hell to read back, maintain, and debug. And the compiler usually outputs much more optimized code that you could ever dream to do, in a fraction of the time.</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