2017-06-20 13 views
0

我有以下代码:错误:'void *'不是指向对象的类型什么是正确的解决方案?

int partition(void* arr, int start, int end, bool(*cmp_f)(void*, void*), 
       void(*swap_f)(void*, void*)) { 
// Point *pivot = &pts[end]; 
    int partition_index = start; 

    for (int i = start; i < end; i++) { 
     if (cmp_f(&arr[i], &arr[end])) {// <---------- Here 
      swap_f(&arr[i], &arr[partition_index]);// <---------- Here 
      partition_index++; 
     } 
    } 
    swap_f(&arr[end], &arr[partition_index]);// <---------- Here 
    return partition_index; 
} 
//------------------------------------------------------------------------------ 
void quick_sort(Point* pts, int start, int end, bool(*cmp_f)(void*, void*), 
       void(*swap_f)(void*, void*)) { 
    if (start < end) {//As long start is less than end we should arrange 
     int pivot = partition(pts, start, end, cmp_f, swap_f); 

     quick_sort(pts, start, pivot - 1, cmp_f, swap_f); 
     quick_sort(pts, pivot + 1, end, cmp_f, swap_f); 
    } 
} 
//------------------------------------------------------------------------------ 

,我得到以下错误:

错误:“无效*”不是一个指针到对象类型

通过观察我发现以下答案:

As the compiler message says, void* is not a pointer to object type. What this means is that you cannot do anything with void*, besides explicitly converting it back to another pointer type. A void* represents an address, but it doesn’t specify the type of things it points to, and at a consequence you cannot operate on it.

来源:In C++, I'm getting a message "error: 'void*' is not a pointer-to-object type"

错误是由以下几行引起的:

cmp_f(&arr[i], &arr[end]); 
swap_f(&arr[i], &arr[partition_index]); 
swap_f(&arr[end], &arr[partition_index]); 

人工铸塑不会是我的代码有帮助的现在的问题是如何,我可以通过改编[指标]到cmp_f或swap_f无需人工铸造?

+3

这基本上是C.如果你是使用C++,拥抱C++并使用模板;这将解决问题 – Justin

+0

您的函数缺少有关缓冲区中对象大小的信息。例如,你不能解引用一个空指针(用'arr [i]')。代码中的问题太重要了,需要重新编写代码。所以我投票结果太宽泛。 – StoryTeller

+0

读一读[good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list),你会看到如何使用模板做到这一点 –

回答

0

您不能将数组作为void *传递,因为在这种情况下元素大小未知,因此您无法访问元素。你必须改变分区函数的签名如下:

int partition(Point* arr, int start, int end, bool(*cmp_f)(Point*, Point*), 
    void(*swap_f)(Point*, Point*)); 

如果分区()必须支持多种类型的使用模板的建议的意见:

template<typename T> int partition(T* arr, int start, int end, bool(*cmp_f)(T*, T*), 
    void(*swap_f)(T*, T*)); 

template<typename T> void quick_sort(T* pts, int start, int end, bool(*cmp_f)(T*, T*), 
    void(*swap_f)(T*, T*)); 
相关问题