Search This Blog

Saturday, October 2, 2010

Managing an array of indeterminate type with void pointers

Programmer Question

I'm trying to write my own Mergesort function in the same fashion as C's qsort function. If I were writing MergeSort for an array of known items, I wouldn't have a problem, but since I don't know what they'll be it's throwing me for a loop.



The specification given by my professor didn't want me to use a separate function for merging, so I'm writing that implementation inside the Mergesort function itself. That means I'll have the same information qsort() would have:




  • void* base - a pointer to the first element of the array to be sorted

  • size_t nel - the number of elements in the array

  • size_t width - the size of each element

  • int (*compar)( const void*, const void* ) - a function that tells you how to compare each element



The problem I'm having is with the Merge part. Every implementation I've seen has used a temporary array to store items while they're sorted. I'm not that used to working with void pointers, and the biggest obstacle I've found is moving through and assigning values into arrays. How would I find the value at the second index in the array pointed to by base? How could I assign a value from that array into a temporary array? How would I create that temporary array?



Would it work if I casted the void pointers to char, and just incremented them by the width? I'm not sure how assignment would work, though.



Find the answer here

No comments:

Post a Comment

Related Posts with Thumbnails