将void指针转换为long类型,而不是指针长?

时间:2015-03-04 03:38:25

标签: c pointers

 int cmpLong(void *a, void *b) {
    long aa = (long)a;
    long bb = (long)b;
    return aa - bb;
}

我真的不明白这段代码的目的是什么呢?当一个void指针被转换为long时,它是一个任意数字还是仍然有一些含义?

我重写了一段代码,以便在void *a and void *b

之间进行比较

以下是我重写的代码:

int cmpLong(void *a, void *b) {
    // casting void pointers to long pointers
    long *aa = (long*)a;
    long *bb = (long*)b;
    return *aa - *bb;
}

这对我来说更有意义,但我不知道它是否与原始代码做同样的事情。

2 个答案:

答案 0 :(得分:2)

这些完全不同。

 int cmpLong(void *a, void *b) {
    long aa = (long)a;
    long bb = (long)b;
    return aa - bb;
}

这是比较两个地址。它将返回两个地址值之间的字节数差异。为了理解这一点,让我们给他们一些数字并玩电脑。

a = 0x2000;
b = 0x1000;
long aa = (long)a; // So aa = 0x1000.  Casting only changes the type, not the value.
long bb = (long)b; // bb = 0x2000.
return aa - bb;    // 0x2000 - 0x1000 => returns 0x1000

现在让我们看看你的例子,这是一个完全不同的事情。

int cmpLong(void *a, void *b) {
    // casting void pointers to long pointers
    long *aa = (long*)a;
    long *bb = (long*)b;
    return *aa - *bb;
}

玩同样的游戏:

a = 0x2000;
b = 0x1000;
long* aa = (long*)a;  // aa = 0x1000.  Casting still doesn't change the value.
long* bb = (long*)b;  // bb = 0x2000.
return *aa - *bb;     // *aa is the data at 0x1000.  This data is treated as a long value.
                      // *bb is the data at 0x2000, again treated as a long value.
                      // so *aa - *bb is the difference between the values at 0x2000 and 0x1000 when read as longs.

答案 1 :(得分:0)

顺便说一句,我刚刚学会了一种很难的方法,你不能将指针强加到long并期望能够将它转换回指针。负指针值将无法在转换中存活:最高位将重复。

也许unsigned long可以工作,但由于我通过swig将值传递给java,而没有无符号整数类型,我无法尝试。