title: Sort words alphabetically using dynamic arrays
body: <p>I came across a question in <strong>C Programming: A Modern Approach</strong> which goes as follows.<a href="https://i.stack.imgur.com/2K5qN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2K5qN.png" alt="enter image description here"></a></p>
  
  <p><strong>I am using <code>qsort</code> from <code>stdlib.h</code> and this is what I have so far:</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  #define MAX_LEN 20
  
  int read_line(char str[], int n);
  static int cmp(const void *p1, const void *p2);
  int main()
  {
  
    char *words[MAX_LEN];
    int i = 0, j;
    char word_str[MAX_LEN + 1], s[20];
  
    for (;;)
      {
        printf("\nEnter a word:  ");
        fgets(s, 20, stdin);
        if (strcmp(s, "\n") == 0)
            break;
        read_line(word_str, MAX_LEN);
      }
  
    int len = strlen(word_str);
    words[i] = malloc(len + 1);
    strcpy(words[i], word_str);
  
    qsort(words, len, sizeof(char *), cmp);
  
    printf("\nIn sorted order:  ");
    for (j = 0; j &lt; len; j++)
      printf("%s ", words[j]);
  
    printf("\n");
  
    return 0;
  
  }
  
  int read_line(char str[], int n)
  {
    int ch, i = 0;
  
    while ((ch = getchar()) != '\n')
      if (i &lt; n)
        str[i++] = ch;
    str[i] = '\0';
    return i;
  
  }
  
  static int cmp(const void *p1, const void *p2)
  {
  
    return strcmp(* (char * const *) p1, * (char * const *) p2);
  
  }
  </code></pre>
  
  <p><strong>The output I receive:</strong>
  <a href="https://i.stack.imgur.com/TTr7w.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TTr7w.png" alt="enter image description here"></a></p>
  
  <p>I am stuck at this point as my compiler does not give me an error and on debugging I see my <code>word_str</code> is empty.</p>
  
  <p>I am new to <strong>c</strong> so please go easy.</p>