2017-02-02 81 views
0

我有一個預分配的結構數組。我試圖構造一個函數,使用該數組作爲輸入,以便我可以構造指向預分配的結構數組的指針數組。然後我想使用qsort對指針數組進行排序,但我似乎誤解了指針傳遞的方式,因爲當我嘗試運行我的代碼時,它是內存訪問衝突的雷區。分配和排序指向現有結構的指針數組

的第一個問題似乎是與行: (&(pRet->ppIndexArray))[i] = &pTestElement[i]; 在sortedIndexPointer我的想法是,ppIndexArray是一個指向指針數組,我需要得到數組的地址指向ppIndexArray然後寫當前TestElement的地址,但這似乎是不正確的。

請參閱我下面簡化代碼:

#include <stdlib.h> 
#include <stdio.h> 

typedef int(*CompareFunction)(const void *, const void *); 

typedef struct TestElement 
{ 
    const char *pName; 
    double data; 
} TestElement; 

typedef struct TestElementIndex 
{ 
    unsigned elementCount; 
    TestElement **ppIndexArray; 
} TestElementIndex; 

int CompareNumbers(const void *p1, const void *p2) { 
    TestElement *pTest1 = *(TestElement **)p1; 
    TestElement *pTest2 = *(TestElement **)p2; 
    if (pTest1->data > pTest2->data) { 
     return 1; 
    } 
    else if (pTest1->data < pTest2->data) { 
     return -1; 
    } 
    else { 
     return 0; 
    } 
} 

TestElementIndex *sortedIndexPointer(TestElement *pTestElement, const unsigned Count, 
            CompareFunction comparer) { 
    TestElementIndex *pRet = malloc(sizeof(TestElementIndex)); 
    pRet->elementCount = Count; 
    pRet->ppIndexArray = malloc(sizeof(TestElement *)*Count); 

    for (unsigned i = 0; i < Count; i++) { 
     (&(pRet->ppIndexArray))[i] = &pTestElement[i]; 
    } 

    if (comparer) { 
     qsort(pRet->ppIndexArray, sizeof(TestElement *), Count, comparer); 
    } 
    return pRet; 
} 

void DisplayElements(const TestElementIndex *pTestElementIndex) { 
    for (unsigned i = 0; i < pTestElementIndex->elementCount; i++) { 
     printf("%lf\n", 
      pTestElementIndex->ppIndexArray[i]->data); 
    } 
} 

int main() { 
    TestElement arr[] = { 
     { "Test1", 5 }, 
     { "Test2", 8 }, 
     { "Test3", 4 }, 
     { "Test4", 9 }, 
     { "Test5", 1 }, 
     { "Test6", 2 }, 
     { "Test7", 0 }, 
     { "Test8", 7 }, 
     { "Test9", 3 }, 
     { "Test10", 6 } 
    }; 
    unsigned Count = sizeof(arr)/sizeof(arr[0]); 
    TestElementIndex *pSorted = sortedIndexPointer(arr, Count, CompareNumbers); 
    DisplayElements(pSorted); 
} 
+0

你應該做的第一件事是在調試器中研究你的各種指針。我敢打賭,10分鐘的調試時間會告訴你到底指向哪裏的錯誤。其他人會嘗試同時檢查你的代碼,但你應該能夠很快得到你自己的答案。 –

回答

1

有你的代碼幾個問題:第一,快速排序參數可以有不同的順序,你想叫

qsort(pRet->ppIndexArray, Count, sizeof(TestElement *), comparer); 

qsort(pRet->ppIndexArray, sizeof(TestElement *), Count, comparer); 

接下來,在填充索引數組時,你不想取數組的地址(地址) ,要在陣列本身,

for (unsigned i = 0; i < Count; i++) { 
    pRet->ppIndexArray[i] = &pTestElement[i]; 
} 

否則,它主要是合理的,檢查http://cpp.sh/5mrxh

+0

非常感謝!我認爲qsort的論點是我在圈子裏運行的。 –

+1

請允許我建議C++,因爲它沒有這樣的問題(編譯器會告訴你你的論點是錯誤的)。 –

+0

我知道,通常使用C++,但在這種情況下,該項目需要我使用C,相信我,我希望我能! –