So i have some code in C where i am trying to build 2 functions 1) \'Read Names\
ID: 3686078 • Letter: S
Question
So i have some code in C where i am trying to build 2 functions 1) 'Read Names', and 2)'Sort Names'
so far everything works, but i cannot figure out how to make 'sortNames' - it is supposed to sort the names in ascending order and print them.
I am using xcode
#include<stdio.h>
#include<string.h>
void readNames(char [][10], int);
void sortNames(char [][10], int);
int main(){
char names[10][10]; //This is the decleration for the 2-D array
int n; //number of students
printf("Please enter number of students: ");
scanf("%d", &n);
readNames(names, n);
sortNames(names, n);
int i;
for(i=0; i<n; i++)
printf("%s ", names[i]);
return 0;
}
void readNames(char names[][10], int n) //reading names function
{
int i;
for(i=0; i<n; i++)
{
printf("Please enter name of %d student: ",(i+1));
scanf("%s", names[i]);
}
}
Explanation / Answer
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int cstring_cmp(const void *a, const void *b)
{
const char **ia = (const char **)a;
const char **ib = (const char **)b;
return strcmp(*ia, *ib);
}
void sortNames(char **names, int len)
{
qsort(names,len, sizeof(char *), cstring_cmp);
return;
}
void readNames(char **names, int n) //reading names function
{
int i;
for(i=0; i<n; i++)
{
printf("Please enter name of %d student: ",(i+1));
scanf("%s", names[i]);
}
}
int main(){
char **names; //This is the decleration for the 2-D array
names = (char **)malloc(sizeof(char *)*10);
int i,n; //number of students
for(i=0;i<10;i++)names[i] = (char *)malloc(sizeof(char)*10);
printf("Please enter number of students: ");
scanf("%d", &n);
readNames(names, n);
sortNames(names, n);
printf("Sorted names: ");
for(i=0; i<n; i++)
printf("%s ", names[i]);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.