This is a toy version of the code I really want to write:

#include <stdio.h>
#include <stdlib.h>

typedef struct node_s {
   char val;
   struct node_s *next;
} node;

int n;

char obtain_next_char(){
   if (n<100) {
      return 'a';
   } else {
      return 0;

int main() {

   char c;
   node *start, *curr;

   n = 0;
   start = malloc(sizeof(node));
   curr = start;

   while ((c=obtain_next_char()) != 0) {
      curr->val = c;
      curr->next = malloc(sizeof(node));
      curr = curr->next;
   curr->next = NULL;

   printf("chain made, %d links\n", n);

   curr = start;

   while (curr != NULL) {


First, regarding obtain_next_char, the function is highly simplified here. With the real function, there is no way to know ahead of time what the return value will be.

Now, the code works, but it results in an empty node at the end of the list, which I'm going to have to get rid of. Can this code be re-written to remedy this deficiency? I am trying to avoid duplicate code at the head of the loop, i.e. I don't want to set up the first node with code outside the loop and then set up the following nodes with the same code inside the loop.


Use a pointer to the previous node next field. This way you can make the first node fall in as the initial value of said pointer. At each iteration you create the new node, populate it (with next == NULL, as it is the last item so far), link it to the previous next and finally update prev_next.

node *start = NULL;
node **prev_next = &start;

while ((c = obtain_next_char()) != 0) {
   node *curr = malloc(sizeof(node));
   curr->val = c;
   curr->next = NULL;

   *prev_next = curr;
   prev_next = &curr->next;

/* start is the list head (or NULL if empty) */
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.