I see what I did wrong, so I retract the last part of my previous comment.
More importantly, I tried this and it did work:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct {
char Col1[10],
Col2[10],
Col3[10];
} Database[] = { {"carla" , "deia" , "m"},
{"brenda", "lilia" , "h"},
{"amanda", "karol" , "c"},
{"amanda", "july" , "b"},
{"brenda", "debora", "a"}};
int Compare(const void *Elemento1, const void *Elemento2) {
return strcmp(
((struct {
char Col1[10],
Col2[10],
Col3[10];
} *)Elemento1)->Col1,
((struct {
char Col1[10],
Col2[10],
Col3[10];
} *)Elemento2)->Col1);
}
int main() {
qsort(Database, 5, sizeof Database[0], Compare);
for(int Reg = 0; Reg < 5; Reg++)
printf("%s\t|%s\t|%s\n", Database[Reg].Col1, Database[Reg].Col2, Database[Reg].Col3);
}
I am still at a loss as to why you wanted to do such an ugly thing, but it is possible. I assume that this is mainly to quench your curiosity, not something you plan to use in production code.
On a side note, I am assuming that this is an example version of the problem, as using opaque names such as col1, col2, etc. would be a bad practice. Perhaps something like this would make more sense:
Code:
struct {
char Personal_name[10],
Middle_name[10],
Surname_initial[10];
} Database[] = { {"carla" , "deia" , "m"},
{"brenda", "lilia" , "h"},
{"amanda", "karol" , "c"},
{"amanda", "july" , "b"},
{"brenda", "debora", "a"}};
As said earlier, though, using a 3-dimensional array would be easier overall:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char Database[][3][10] = { {"carla" , "deia" , "m"},
{"brenda", "lilia" , "h"},
{"amanda", "karol" , "c"},
{"amanda", "july" , "b"},
{"brenda", "debora", "a"}};
int Compare(const void *Elemento1, const void *Elemento2) {
return strcmp(((char *)Elemento1), ((char *)Elemento2));
}
int main() {
qsort(Database, 5, sizeof Database[0], Compare);
for(int Reg = 0; Reg < 5; Reg++)
printf("%s\t|%s\t|%s\n", Database[Reg][0], Database[Reg][1], Database[Reg][2]);
}
I know you said you needed it to be a struct, but you never said why.