Home > Back-end >  assigning a void pointer to another
assigning a void pointer to another

Time:08-20

I am working on this method that should operate the insertion sort on a given array of unknown type

void binary_insertion_sort(void** array, size_t size, int (*compare)(void**,void**)){
  int i,j,destination;
  void* moving;
  for(i=1;i<(int)size;i  ){
    j=i-1;
    moving=array[i];        
     //here I have serious doubts about this assignment
    destination=binary_search(array,moving,0,j,(*compare));
    while(j>=destination){
      swap(&array[j 1],&array[j]);
      j--;
    }
    array[j 1]=moving;      //here I have the same problem
  }  
}

I was thinking about doing something like memcpy() but I still don't know the size of the type.

CodePudding user response:

If you want to sort an array whose element type is unknown to you, then you should use the signature of the standard qsort() function, which does exactly the same job. The signature presented in the question is similar, but not the same, and I see no good reason for the difference if the function's job is what you describe.

I was thinking about doing something like memcpy() but I still don't know the size of the type.

No, you don't, unless the the caller tells you. That information is not carried by type void * (nor type void **). That's why the arguments to qsort() are, and those to your function should be,

  • a pointer to the first element of the array (type void * would be the most appropriate for that)
  • the number of elements in the array
  • the size of the element type
  • a pointer to a comparison function that accepts pointers to array elements as arguments (again, void * is the most appropriate type for this).

HOWEVER, if the problem were slightly different, say "sort an array of pointers to void based on the order defined by a user-defined function that compares the objects to which the pointers point", then you don't need the size of the pointed-to objects, because you never need to move them. You move only the pointers. That might have this signature:

void binary_insertion_sort(void *array[], size_t nmemb, int (*compare)(void *, void *));

, which is equivalent to this:

void binary_insertion_sort(void **array, size_t nmemb, int (*compare)(void *, void *));

Note the difference between this comparison function and your example. This describes a sort specifically of arrays of void *, where the sort order is user-defined and might depend on the pointed-to objects. You don't need the size of the pointed to objects here, because what you're supposed to sort (and therefore swap) is the pointers:

void *p1, *p2;
// ...
void *tmp = p1;
p1 = p2;
p2 = tmp;
  • Related