繁体   English   中英

从Q中的C中的结构数组检索结构

[英]Retrieving struct from array of struct in C for qsort

我正在尝试从结构数组中的结构中检索两个值,但是我不知道自己在做什么错。 我需要这个qsort

这是我的代码示例:

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

但是,如果我尝试为qsort编写一个编译器函数,则会给我一个错误(请求成员“ data1”而不是结构或联合):

int comp (test* first, test* second){
    return first->data1 - second->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;
    }

问题是您的typedeftest定义为指针类型,而不是普通类型。 然后test*成为双指针,即struct test** 当您编写first->data1 ,您将->运算符应用于指向struct test的指针,而不是指向struct的指针。

由于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*并强制转换为test* ,因为qsort需要一个函数指针,该函数指针需要一对恒定的void指针。 简单地转换一个函数指针将可以编译甚至可以工作,但是行为是不确定的。

typedef struct test *test;

这也可以写成

typedef struct test* test;

因此,现在测试已经是一个指针。 所以当你写

test *first;

它成为了

struct test **first;

你应该有类似的东西

typedef struct test test;

然后

test *first ;

first将具有指向您的结构的指针。

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

first->data1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM