Hey hombres. I feel a bit embarassed to ask something so simple,but i need help with qsort.
As you will understand,im trying to sort my table made of "catPage" structs,which are read from keyboard,comparing the lName strings.
First i print the struct array unsorted,then sorted,but what i see printed is 2 times the same unsorted array. In other words,i get no compiler errors from qsort,but it simply does nothing. (I have been stuck here for a good 4 hours,i decided to give up and ask help :P)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct catPage {
char name[20];
char lName[20];
///char address[40];
int pNumber;
///char email[20];
};
struct catPage catalogue[50];
int catFreeEntry=3;
int rep;
int i;
int choice=3;
void appendEntry(struct catPage ca);
struct catPage getCatPage(struct catPage ca);
const int myCompare (const void *a, const void *b) ;
void qsort(void *base, size_t count, size_t size, int (*comp)(const void *e1, const void *e2));
int main(int argc, char *argv[])
{
struct catPage cat;
struct catPage catalogue[50];
while(choice!=0) {
printf("\n1 to add Contact(s), 2 to view contacts,0 to exit");
scanf("%d",&choice);
if (choice==1){
printf("How many contacts to add?\n");
scanf("%d",&rep);
if (rep<0||rep>100) break;
for (i=0;i<rep;i++) {
cat=getCatPage(cat);
appendEntry(cat);
}
}
if (choice==2){
for (i=0;i<catFreeEntry;i++){
printf("%-8s -- %8s %8d\n",catalogue[i].name,catalogue[i].lName,catalogue[i].pNumber);
}
printf("\n <test>2o format ->\n");
size_t structs_len = sizeof(catalogue) / sizeof(struct catPage);
qsort (catalogue,structs_len,sizeof(struct catPage),myCompare);
for (i=0;i<catFreeEntry;i++){
printf("%-8s -- %8s %8d\n",catalogue[i].name,catalogue[i].lName,catalogue[i].pNumber);
}
}
}
system("PAUSE");
return 0;
}
struct catPage getCatPage(struct catPage ca){
printf("\nname\n");
scanf("%s",ca.name);
printf("last name\n");
scanf("%s%*c",ca.lName);
printf("number\n");
scanf("%d",&ca.pNumber);
return ca;
};
void appendEntry (struct catPage ca) {
strcpy(catalogue[catFreeEntry].name,ca.name);
strcpy(catalogue[catFreeEntry].lName,ca.lName);
catalogue[catFreeEntry].pNumber=ca.pNumber;
catFreeEntry++;
};
int myCompare (const void *a, const void *b) const {
struct catPage *ia = (struct catPage *)a;
struct catPage *ib = (struct catPage *)b;
return strcmp(ia->lName, ib->lName);
}