Answer to Question #181257 in C for jake

Question #181257

Write a program that will sort a list of strings (names of person) enter by the user given the value of names.


1
Expert's answer
2021-04-15T00:08:27-0400
#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();


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS