我有一個預分配的結構數組。我試圖構造一個函數,使用該數組作爲輸入,以便我可以構造指向預分配的結構數組的指針數組。然後我想使用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);
}
你應該做的第一件事是在調試器中研究你的各種指針。我敢打賭,10分鐘的調試時間會告訴你到底指向哪裏的錯誤。其他人會嘗試同時檢查你的代碼,但你應該能夠很快得到你自己的答案。 –