I have a struct
struct info {
char firstName[100];
char lastName[100];
char companyName[100];
char email[100];
unsigned long phoneNumber;
};
which is stored in the file compareElements.h
I read in a set of values into a dynamically allocated array of structs called bptr.
my comparePtr points to this function.
#include <string.h>
#include "compareElements.h"
int compareNameAscending (const void *a, const void *b) {
struct info *part1 = (struct info *) a;
struct info *part2 = (struct info *) b;
if(part1 -> lastName[0] != '\0' && part2 -> lastName[0] != '\0') {
return (strcmp(part1 -> lastName , part2 -> lastName));
}
if (part1 -> lastName[0] == '\0' && part2 -> lastName[0] != '\0') {
return (strcmp(part1 -> companyName , part2 -> lastName));
}
if (part1 -> lastName[0] != '\0' && part2 -> lastName[0] == '\0') {
return (strcmp(part1 -> lastName, part2 -> companyName));
}
if (part1 -> lastName[0] == '\0' && part2 -> lastName[0] == '\0') {
return (strcmp(part1 -> companyName, part2 -> companyName));
}
}
In the main function I have
comparePtr = &compareNameAscending
The problem is that not all structs need to have a lastName and companyName only one of the two. So I want to sort by last name, and if they don't have a last name I'll sort by company name. The problem is that my qsort call doesn't ever actually change the order of the struct it just spits out the original. This is the qsort call.
qsort(bptr, i, sizeof(struct info), comparePtr);