That I have?
I have a structure with several elements of the same type
struct tipo_t
{
char elemento_1[8192];
char elemento_2[8192];
char elemento_3[8192];
char elemento_4[8192];
.
.
}
I also have an array of structures of that type (which I read and fill per file)
tipo_t *array = malloc(longitud*sizeof(tipo_t));
array[longitud];
Then I sort it using the qsort() function from the C library whose declaration is this:
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
And that for my particular case is this way
qsort (array, longitud, sizeof(tipo_t), comparaPorElemento1);
I have a compare function for item 1:
int comparaPorElemento1 (const void * a, const void * b)
{
tipo_t *A = (tipo_t *)a;
tipo_t *B = (tipo_t *)b;
return ( strcmp( B->elemento_1, A->elemento_1 ) );
}
What do I want?
Now what I want is to be able to select by which element to order the array of structures. not only for element 1 but for any of the elements, after searching through several internet sites the answer I got was that I had to do a comparison function for each element to be compared, and although this solution works I wondered if there would be another way.
I thought maybe I could add another element to the structure that would be the element to compare
struct tipo_t
{
char elemento_1[8192];
char elemento_2[8192];
char elemento_3[8192];
char elemento_4[8192];
.
.
char comparate[8192];
}
And that prior to the qsort instruction select the element to compare and exchange it for the compare element , however it seems to me that this would decrease the performance of the program. So I tried to think of some way that the copy to the compare element would be done quickly and I thought that with joins something might happen, but I abandoned that idea because I don't think I can do anything there.
Doing the comparison functions is also nothing to be afraid of, because it's basically a few ctrl+c ctrl+v, but you'll understand that it's okay to ask if there's no other way.
Thank you so much
I propose a solution.
From what I see, you
strut
are nothing more than a set of strings, all the same size. So you can use an offset inside the structure to select the string to compare.I haven't tried it , but with minor changes it should work.
As is, it compares by the first element.
To indicate another element, we do
From that moment on, the comparisons would be made
elemento_3
by comparing the structure.This solution is exclusive to your
struct
, which, as I said, is nothing more than a group of fields of the same type.