Hello again, I struggled for a few hours with this one but I can't seem to find what I am looking for, so thank you in advance for any help. I am trying to do the following exercise:
Write a program that sorts a series of words entered by the user. Assume that each word is no more that 20 characters long. Stop reading when the user enters an empty word. Store each word in a dynamically allocated string, using any array of pointers to keep track of the strings. After all words have been read, sort the array (using any sorting technique) and then use a loop to print the words in sorted order.
Here is what I have written:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define MAX_WORD 20
#define NUM_WORDS 10
int read_word(char *, int);
int main(int argc, char **argv) {
char *words_vector[NUM_WORDS];
char word[MAX_WORD + 1];
int i, j, word_len, index = 0;
char *temp;
for(;;) {
if(index == NUM_WORDS) {
printf("\n---word vector is full---\n");
break;
}
printf("Enter word: ");
word_len = read_word(word, MAX_WORD);
if(word_len == 0)
break;
*(words_vector + index) = malloc(word_len);
if(*(words_vector + index) == NULL) {
printf("\nmalloc failed in element %d of words_vector!\n", index);
exit(EXIT_FAILURE);
}
strcpy(*(words_vector + index), word);
++index;
}
printf("\nIn unsorted order:");
for(i = 0; i < index; ++i)
printf(" %s", *(words_vector + i));
for(i = 0; i < index - 1; ++i)
for(j = i + 1; j < index; ++j)
if(strcmp(*(words_vector + i), *(words_vector + j)) > 0) {
temp = *(words_vector + j);
*(words_vector + j) = *(words_vector + i);
*(words_vector + i) = temp;
}
printf("\nIn sorted order:");
for(i = 0; i < index; ++i) {
printf(" %s", *(words_vector + i));
free(*(words_vector + i));
}
return 0;
}
int read_word(char *str, int n) {
int c, i = 0;
while(!isspace(c = getchar()))
if(i < n)
*(str + i++) = c;
while(c != '\n')
c = getchar();
*(str + i) = '\0';
return i;
}
The program "seems" to work fine, but 1 out of 20 crashes. That made me think that I definitely messed up somewhere. I spend a few hours experimenting but I can't see my error. The time the program crashes, is after I enter some word (random from the 1rd to 10th) and same input words, doesn't seem to be the issue.
Any hint to point my error, will be valuable.
Also do not mind my sorting, I intend to rewrite the same program using qsort and then again with a "hand made" implementation of the quicksort algorithm. But if you have any suggestion about how to better write my code will be much appreciated.
Cheers