"There is a structure consisting of various fields. There is also an array of these structures. Purpose: to write a universal function that would sort the array according to the field selected by the user." Question: Is it possible to do this at all in C without using a heap of if
constructions? If so, how can you dynamically access the required structure field? I thought it would be like dancing from a pointer to the base address of the structure in memory, but that would work if all the fields occupied an equal number of bytes.
1 answer
Of course, you can do without a lot of if'ov. You should write or find on C some of the standard sorting algorithms ( inserts , pyramid , merge , fast ) and add references to the fields of your structures. That is, where in the usual sorting of numbers the reference goes directly to the array element, you need to refer to the array element field.
In the standard C ++ library there are ready-made sorting algorithms, there only array iterators and the comparison function should be sent. It is possible that on the Internet there is something similar ready for C.
And it would be better to store not an array of structures, but an array of pointers to structures, so as not to waste time copying the values of the structures when they are swapped. In general, this is one of the reasons for the existence of pointers.