简体   繁体   English

如何将const void *转换为struct元素?

[英]How can I cast a const void* to a struct element?

I have my comparison function to use in qsort() like this: 我有我的比较函数在qsort()中使用如下:

int compar(const void *p, const void *q){
    interval a,b;

    *p = (interval)a
    *q = (interval)b;

    if(a.extrem[1] < b.extrem[0])
        return -1;
    if(b.extrem[1] < a.extrem[0] )
        return 1;

    return 0;
}

My structure is as follows: 我的结构如下:

typedef struct interval{
    double extrem[2];
    } interval;

I've tried many variations of "casting" in function compar, which all failed. 我在函数比较中尝试了许多“cast”变体,但都失败了。 My question, as it is apparent, how can I cast a const void* to my struct element? 我的问题,很明显,我如何将const void *转换为我的struct元素? I know it seems to be a very basic question but I could not find a clear answer anywhere, also I'm new to this. 我知道这似乎是一个非常基本的问题,但我无法在任何地方找到明确的答案,我也是新手。 Any help is gladly appreciated. 任何帮助都很高兴。

You were close... 你很亲密......

typedef struct interval {
  double extrem[2];
} interval;

int compar(const void *p, const void *q) {
  const interval *a = p, *b = q;

  if(a->extrem[1] < b->extrem[0])
    return -1;
  if(b->extrem[1] < a->extrem[0])
    return 1;
  return 0;
}

BTW, without a single cast, this will be perfectly clean under gcc -Wall. 顺便说一句,没有一个演员阵容,这将在gcc -Wall.下完全清晰gcc -Wall.

Update... Tavian makes a good point, this is not a transitive ordering, so your set technically has no partial order. 更新... Tavian提出了一个很好的观点,这不是一个传递性的排序,所以你的设置在技术上没有偏序。 But depending on your data and your objective, qsort may return a useful result even so. 但是,根据您的数据和目标,qsort可能会返回有用的结果。

The qsort() function is going to call your callback with pointers to the elements. qsort()函数将使用指向元素的指针调用回调函数。

Assuming the array is an actual array of interval , not one of interval pointers, you'd do: 假设数组是一个实际的interval数组,而不是间隔指针之一,你可以这样做:

static int interval_compare(const void *a, const void *b)
{
  const interval *ia = a, *ib = b;

  if(ia->extrem[1] < ib->extrem[0]) return -1;
  return ib->extrem[1] > ia->extrem[0];
}

I don't understand the extrem indexes, but that's what you used. 我不了解extrem索引,但这就是你所使用的。 No casts are necessary when converting void * to a more specific type. void *转换为更具体的类型时,不需要强制转换。 See this answer . 看到这个答案

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

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