YellowPillow - 1 year ago 67
C Question

# Casting void pointer to long type, not pointer long?

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

I don't really understand the purpose of this piece of code what is it comparing? When a void pointer is casted as a long is it an arbitrary number or does it still hold some meaning?

I have re-written the piece of code to allow for comparison between
`void *a and void *b`

Here is the code that I have re-written:

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

This makes more sense to me but I don't know whether it is doing the same thing as the original code.

Answer Source

These do different things entirely.

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

This is comparing two addresses. It will return the number of bytes difference between the two address values. To understand this, let's give them some numbers and play computer.

``````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
``````

Now let's look at your example, which is doing quite a different thing.

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

Playing the same game:

``````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.
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download