从C中用于qsort的结构数组中检索结构

从C中用于qsort的结构数组中检索结构,c,arrays,struct,C,Arrays,Struct,我试图从struct数组中的struct中检索两个值,但我不知道我做错了什么。我需要这个 下面是我的代码示例: typedef struct test { int data1; int data2; } *test; 然后我创建一个struct数组并返回指向该数组的指针: test* foo(**some args**) test* array = malloc(sizeof(proc)); int currentElement = 0; while(.

我试图从struct数组中的struct中检索两个值,但我不知道我做错了什么。我需要这个

下面是我的代码示例:

typedef struct test {
    int data1;
    int data2;
} *test;
然后我创建一个struct数组并返回指向该数组的指针:

test* foo(**some args**)
    test* array = malloc(sizeof(proc));
    int currentElement = 0;
    while(...){
        // get some data
        // and make space for struct
        array[currentElement] = malloc(sizeof(struct test));
        // add data to struct
        array[currentElement] -> data1 = ...;
        array[currentElement] -> data2 = ...;
        // resize array for the next wave of structs
        array = realloc(array, (currentElement + 1) * sizeof(struct proces));
        currentElement++;
    }
    return array
当我尝试访问并打印数组中的结构时,numberOfElement是一个全局变量:

void printData(test* a) {
    printf("%s\n", "Data");
    int i;
    for (i = 0; i < numberOfElements; i++) {
        printf("%5d\n",
                a[i]->data1
                );
    }
}
编辑:添加返回指向结构数组指针的函数foo。谢谢dasblinkenlight

我还有一个问题:

这管用

int comp (void *a, void* b){
    test* first = (test*)a;
    test* second = (test*)b;
    return (*first)->data1 - (*second)->data1;
}
当我尝试对数组进行如下排序时:

test* a = foo(...);
qsort(a, numberOfElements, sizeof(test), comp);
printData(a);
这给了我一个错误:

warning: passing argument 4 of ‘qsort’ from incompatible pointer type [enabled by default]
In file included from Naloga2.c:2:0:
/usr/include/stdlib.h:765:13: note: expected ‘__compar_fn_t’ but argument is of type ‘int (*)(void *, void *)’
 extern void qsort (void *__base, size_t __nmemb, size_t __size,
编辑2:最终解决方案

int comp (const void *a, const void* b){
        test* first = (test*)a;
        test* second = (test*)b;
        return (*first)->data1 - (*second)->data1;
    }
问题是typedef将test定义为指针类型,而不是普通类型。然后test*变成双指针,即struct test**。当您首先写入->数据1时,您将->运算符应用于指向指向结构测试指针的指针,该指针不是指向结构的指针

由于test*是一个双指针,您需要重写comp以在获取成员之前取消引用它一次,如下所示:

int comp (const void *a, const void* b){
    const test* first = (const test*)a;
    const test* second = (const test*)b;
    return (*first)->data1 - (*second)->data1;
}
您需要在内部将void*和cast传递给test*,因为qsort需要一个函数指针,它接受一对常量void指针;简单地强制转换函数指针将编译,甚至可能工作,但行为将是未定义的

typedef struct test *test;
这也可以写成

typedef struct test* test;
所以现在test已经是一个指针了。所以当你写作的时候

test *first;
它变成

struct test **first;
你应该吃点类似的东西

typedef struct test test;
然后

将第一个作为指向您的结构的指针

这样可以确保comp所期望的参数是一个指针,并且访问保持良好

first->data1

1删除typedef 2将struct test*作为参数发送,并将varray更改为struct test*并进行检查。这可能会解决问题。错误:从不兼容的指针类型[默认情况下启用]传递'qsort'的参数4,请您跳过示例代码好吗?这很有效,谢谢。但现在我有另一个问题,看看编辑理论,我忘了添加常量。编辑应该修复警告。谢谢@dasblinkenlight!
test *first ;
first->data1