我有一个预先分配的结构数组。我正在尝试构造一个使用该数组作为输入的函数,以便我可以构造一个指向预分配结构数组的指针数组。然后我想使用 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);
}
最佳答案
您的代码几乎没有问题:首先,qsort参数有不同的顺序,您想调用
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 .
关于c - 分配和排序现有结构的指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42009503/