2017-06-20 9 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); 
    } 
} 
//------------------------------------------------------------------------------ 

を、私は次のエラーを取得する:

エラー:「void *型は」私が見つけた見ることで、ポインタとオブジェクトタイプ

ではありません次の答え:

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]); 

マニュアル鋳造は今、私の質問は、私は手動で鋳造することなく、ARR cmp_fする[インデックス]またはswap_fを渡すことができる方法である私のコードに役立つのではないでしょうか?

+3

これは基本的にCです。 C++を使用し、C++を採用し、テンプレートを使用します。これにより問題が解決されます – Justin

+0

バッファ内のオブジェクトのサイズに関する情報が関数にありません。たとえば、voidポインタ( '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*)); 
関連する問題