Imtiaz Raqib Imtiaz Raqib - 13 days ago 5
C Question

Sort words alphabetically using dynamic arrays

I came across a question in C Programming: A Modern Approach which goes as follows.enter image description here

I am using

qsort
from
stdlib.h
and this is what I have so far:


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

#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 < 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 < 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);

}


The output I receive:
enter image description here

I am stuck at this point as my compiler does not give me an error and on debugging I see my
word_str
is empty.

I am new to c so please go easy.

Answer

I see the following problems in your code.

Problem 1

The code to save the lines of text in words needs to be inside the for loop.

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);
}

Problem 2

You don't have a counter to keep track of the number of lines read.

Use:

int num_lines = 0;
for (;; ++num_lines)
{
  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[num_lines] = malloc(len + 1);
  strcpy(words[num_lines], word_str);
}

Problem 3

You are passing the wrong value in the second argument to qsort. You need to pass num_lines, not the length of the last string.

qsort(words, num_lines, sizeof(char *), cmp);

Problem 4

Don't use len in the conditional of the for loop when printing the sorted strings. Use num_lines instead.

for (j = 0; j < num_lines; j++)
  printf("%s ", words[j]);
Comments