Here are the instructions:
Write a program that sorts a series of words entered by the user:
Enter word: foo
Enter word: bar
Enter word: baz
Enter word: quux
Enter word:
In sorted order: bar baz foo quux
Assume that each word is no more than 20 characters long. Assume there are no more than 50 words to be sorted. Stop reading when the user enters an empty word (i.e., press Enter without entering a word). Store each word in a dynamically allocated string, using an array of pointers to keep track of the strings. After all the words have been read, sort the array and then print the words in a sorted order.
Hint:
1) Use the read_line function (textbook, page 287 or slide 20, July 2 lecture) to read each word.
2) Use qsort function in <stdlib.h> to sort an array of strings.
I have been getting the following error and warning when I attempt to compile:
sort_words.c:18: error: invalid operands to binary *
sort_words.c:30: warning: comparison between pointer and integer
Where exactly did I go wrong? What do I have to do to get the words to sort in order?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define WORD_LEN 50
#define WORD_LIMIT 20
int read_line(char str[], int n);
int int_compare(const void* p, const void* q);
int main()
{
char n[WORD_LIMIT];
int i;
int *a;
a = malloc(n * sizeof(char));
for(i = 0; i < WORD_LEN; i++)
{
printf("Enter a word: ");
scanf("%c", &n[i]);
}
qsort(n, WORD_LEN, sizeof(char), int_compare);
printf("In sorted order:\n");
for(i = 0; i < n; i++)
printf("%c\t", a[i]);
printf("\n");
return 0;
}
int int_compare(const void* p, const void* q){
int n1 = *(int *) p;
int n2 = *(int *) q;
if (n1 < n2)
return -1;
if (n1 == n2)
return 0;
return 1;
}
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;
}