-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sort words
62 lines (53 loc) · 1.35 KB
/
Sort words
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_WORDS 50
#define WORD_LEN 20
int read_line(char str[], int n);
int compare_strings(const void* p, const void* q);
int main(void)
{
char* words[MAX_WORDS], word[WORD_LEN + 1];
int i, num_words = 0;
for (;;) {
if (num_words == MAX_WORDS) {
printf("--No space left--\n");
break;
}
printf("Enter a word: ");
read_line(word, WORD_LEN);
if (strlen(word) == 0) {
break;
}
words[num_words] = malloc(strlen(word) + 1);
if (words[num_words] == NULL) {
printf("--No space left--\n");
break;
}
strcpy(words[num_words], word);
num_words++;
}
qsort(words, num_words, sizeof(char*), compare_strings);
printf("\nIn sorted order : \n");
for (i = 0; i < num_words; i++)
printf(" %s\n", words[i]);
printf("\n");
// Free memory allocated for each word
for (i = 0; i < num_words; i++)
free(words[i]);
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;
}
int compare_strings(const void* p, const void* q)
{
return strcmp(*(char**)p, *(char**)q);
}