title: C Sorting trouble
body: <p>How do I sort the occurrence of each word in descending order? </p>
  
  <p>My current code is:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;stddef.h&gt;
  #include &lt;ctype.h&gt;
  #include &lt;string.h&gt;
  
  #define WORDLEN 50
  
  typedef struct node_struct NODE;
  struct node_struct {
    char *word;    
    int count;
    NODE *next;
  };
  
  /*compare and adds words to the list*/
  NODE *new_node(char *word, NODE *head) {
    NODE *p = head;
    char *s;
  
    if (p == NULL) {
      p = (NODE*)malloc(sizeof(NODE));
      s = (char*)malloc(sizeof(strlen(word) + 1));
      strcpy(s, word);
      p-&gt;word = s;
      p-&gt;count = 1;
      p-&gt;next = head;
      return p;
    }
    for (; p-&gt;next != NULL &amp;&amp; strcmp(p-&gt;word, word) != 0; p = p-&gt;next);
    if (strcmp(p-&gt;word, word) == 0) {
      p-&gt;count += 1;
      return head;
    }else{
      p-&gt;next = (NODE*)malloc(sizeof(NODE));
      p = p-&gt;next;
      s = (char*)malloc(sizeof(strlen(word) + 1));
      strcpy(s, word);
      p-&gt;count = 1;
      p-&gt;word = s;
      p-&gt;next = NULL;
      return head;
    }
  }
  /*gets words*/
  char *getword(char *w, int n)
  {
    int i = 0;
    int c;
  
    if (n &lt;= 0 || feof(stdin))
      return NULL;
    c = getchar();
    while (c != EOF &amp;&amp; ! isalpha(c)) {
      c = getchar();
    }
    if (c == EOF)
      return NULL;
    while (isalpha(c)) {
      if (i &lt; n - 1) {
        w[i] = toupper(c);
        i++;
      }
      c = getchar();
    }
    w[i] = '\0';
    return w;
  }
  /*print*/
  void print(NODE *p) {
    for (; p != NULL; p = p-&gt;next) {
      printf("%s %d\n",p-&gt;word, p-&gt;count);
    }
    printf("\n");
  }
  
  int main()
  {
    char w[WORDLEN];
    NODE *p = NULL;
    int i;
  
    while (getword(w, WORDLEN) != NULL) {
   p = new_node(w, p);
    }
    print(p);
      return 0;
    }
  </code></pre>