I've written up a large collection of abstract data types (ie: hash tables, heaps, etc) and simple algorithms (ie: search, sort, list manipulation, etc) that all work on arrays of int
. I've modified some of my algorithms to be like what I have below so I can generalize the code without re-writing the same algorithm for each and every data type I want to sort/compare:
void* bubbleSort(void* inputArray, void (*functionPtr)(void*,void*)), size_t dataTypeSize, size_t numElements)
The idea is that I want to be able to sort an array of any arbitrary data type (ie: custom struct
s), and to accommodate this, I cast the input array as a pointer-to-void, and the sorting algorithm requires a function pointer to a specific comparison function so it knows how to compare any two elements of the same data/struct type. So far so good.
The one thing I can't figure out is how to properly cast the array within the function so I can access a single element at a time. I'm trying to accomplish something like:
someRandomDataType* tempArray = (someRandomDataType*)inputArray;
However, I can't find any means of doing this at run time without the use of macros (which I'd like to avoid in this case if possible). It seems in my case, all I really need to be able to do is cast inputArray
so that it is seen as some array with elements of an arbitrary size. Is there some way to cast a pointer-to-array so that, dynamically, it equates to:
(typeThatIsDataTypeSize*) tempArray = (typeThatIsDataTypeSize*)inputArray;
Where "dataTypeSize" refers to the size_t
input value passed to the sorting function? Thanks!
Your bubble function already has all the information. size
, which is equal to sizeof element you are containing and count the number of elements.
inputArray
points to the very first element. When you want to move to the next element you simply increase the pointer by the size of the element.
void* second_element = ( char* )inputArray + size ;
size_t n = 123 ;
void* nth_element = ( char* )inputArray + size * n ;
This is how you index your array.
Moving elements is done by memcpy with the last parameter is size
. And swap is done by declaring temporary memory of size size
and using memcpy to move memory around.