简体   繁体   English

使用qsort对2D数组进行排序-正确的类型转换

[英]Sorting 2D arrays with qsort - correct typecasting

I am having a problem with using c++ qsort compare function to correctly lexicographically sort 2d array of ints. 我在使用c ++ qsort compare函数正确按字典顺序对2d数组进行排序时遇到问题。 I have already read many similar questions here but with no success. 我已经在这里阅读了许多类似的问题,但是没有成功。 When making the custom compare function, its arguments are in form of 进行自定义比较功能时,其参数采用以下形式:

int compar (const void* p1, const void* p2)

now, I know that it the arguments are pointers to my variables, that are each ponters to one row of my array. 现在,我知道参数是指向我的变量的指针,每个变量都指向数组的一行。 I would like to index and compare my array in the normal conventional way using something like the following. 我想使用类似于以下内容的常规常规方式对数组进行索引和比较。

if(p1[0] <= p2[0]) {...}

Because I know, that the format 因为我知道,格式

p1[i]

is just a shortcut for pointer arithmetic, I guess when I am recieving an argument "pointer to pointer to int", I should typecast and use it this way: 只是指针算术的捷径,我想当我收到一个参数“指向int的指针”时,我应该打字并以这种方式使用它:

if(*(int**)p1[0] <= *(int**)p2[0]) {...}

Compiler however gives me many these errors 但是编译器给了我很多这些错误

main.cpp:8:20: error: ‘const void*’ is not a pointer-to-object type
main.cpp:8:37: warning: pointer of type ‘void *’ used in arithmetic  [-Wpointer-arith]

My question is, how to correctly typecast this, so it would allow me to compare my rows. 我的问题是,如何正确键入此内容,以便可以比较行。 Also, I would like to understand, what am I doing wrong here to avoid making these pointer related mistakes in the future. 另外,我想了解一下,在这里我在做什么错,以避免将来再犯这些与指针相关的错误。

It's because operator[] takes precedence over cast. 这是因为operator[]优先于强制转换。 b[0] is trying to be resolved first. b[0]正在尝试首先解决。 So even if it's b[0] it complains you are doing pointer arithmetic on void* type. 因此,即使它是b[0]它也会抱怨您正在对void*类型进行指针算术运算。 You need to cast 1st. 您需要投第一名。

#include <iostream>
using namespace std;

int main() {
    int a[10];
    a[0] = 1337;
    a[1] = 42;
    void* b;
    b = (void*)a;

    //  cout << (int*)b[0] << '\n'; // will break
    cout << ((int*)b)[0] << '\n';

    // dedicated c++ cast imposes more verbose syntax - i.e. you can't miss the ()
    cout << static_cast<int*>(b)[1] << '\n';
    return 0;
}

That being said I still would encourage to use c++ dedicated features for what you're doing =). 话虽如此,我仍然鼓励您使用c ++专用功能进行操作=)。

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

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