I have a structure for every user and I'm trying to sort them by users Lastname
Full code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct phNum
{
char name[30];
char lastName[30];
int phone;
};
typedef struct phNum PhNum;
PhNum phList[5] = {};
void showData() {
for(int i = 0;i < 5;i++) {
if(strcmp(phList[i].name,"empty") == 0 && phList[i].phone == 0){
printf("%d : %s | %s | null\n", i+1,phList[i].name,phList[i].lastName);
}
else {
printf("%d : %s | %s | %d\n", i+1,phList[i].name,phList[i].lastName,phList[i].phone);
}
}
}
The array maximum is 5 items and the minimum is 0
I want to sort them ascending by their Lastname and if there are 4 items don't show the fifth one.
and I want to override my Array phList and rewrite the sorted one
my showData function is supposed to sort and print
I tried These answers but I didn't understand: How to sort an array of structs in C? and
How do I sort an array of structs in C by name, age and id?
I also tried to make a bubble sort algorithm but I was struggling to put my sorted data into my phList
Thanks For Help
qsortfunction.struct PhNum", and return an integer. The function should return a negative number if the first argument is "less" than the second, zero if both are equal, or a positive value if the first argument is "greater" than the second argument. Fortunately there already exists a standard function that return exactly that when comparing strings:strcmp. So callstrcmpto compare thelastNameof the two structures, and return the result. Now you have a function you can basically plug in directly for theqsortfunction.qsort, to sort any kind of arrays. Including arrays of structures. Experiment, and try something for yourself. That's a good way to learn.qsortand sorts a plain int array.