This is a follow-up to this post.
Things I've changed:
- The number of strings is checked.
- I'm using pointers now.
I'll use fgets
in more mission critical situations. For a lab assignment, the scanf
approach will suffice I hope.
#include <stdio.h> #include <stdlib.h> #include <string.h> #define LEN 100 #define WID 80 void sort(char *s[], int n); void display(char *s[], int n); int main() { int n, i; char *s[LEN]; printf("Enter number of strings : "); scanf("%d", &n); printf("Enter strings one by one :\n"); if (n > LEN) { printf("Sorry, maximum strings allowed is %d. Defaulting.", LEN); n = LEN; } for (i = 0; i < n; i++) { printf("%d : ", i + 1); s[i] = (char *) malloc(WID * sizeof(char)); scanf(" %s", s[i]); } printf("The initial elements are:\n"); display(s, n); sort(s, n); printf("The elements after sorting are:\n"); display(s, n); return 0; } void sort(char *s[], int n) { char *temp; int item, i; for (item = 1; item < n; item++) { temp = s[item]; for (i = item; i > 0 && strcmpi(s[i - 1], temp) > 0; i--); memcpy(&s[i + 1], &s[i], (item - i) * sizeof(char *)); s[i] = temp; } } void display(char *s[], int n) { int i; printf("\n\n"); for (i = 0; i < n; i++) { printf("%s ", s[i]); } printf("\n\n"); }
Any alternative or more elegant approach is welcome.