Write a program that will sort a list of strings (names of person) enter by the user given the value of n names.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int compareNames(const void* name1, const void* name2){
return strcmp(*(const char**)name1, *(const char**)name2);
}
int main(){
int n,i;
const int SIZE=30;
char** names = malloc(sizeof(char *)*SIZE);
//get the number of names
printf("Enter the number of names (n): ");
scanf("%d",&n);
for (i=0; i<n; i++){
names[i] = (char *)malloc(sizeof(char)*n*SIZE);
}
//get the names from the user
for(i=0;i<n;i++){
printf("Enter name: ");
scanf("%s",names[i]);
}
//sort names
qsort(names, n, sizeof(const char*), compareNames);
//Display sorted names
printf("\nSorted names:\n");
for(i=0;i<n;i++){
printf("%s\n",names[i]);
}
//free allocated memory
for(i=0;i<n;i++){
free(names[i]);
}
free(names);
//delay
getchar();
getchar();
}
Comments
Leave a comment