问题
Am I right in thinking it is fine to treat a pointer as an int for the purposes of sorting an array of pointers, e.g.
qsort(ptrs, n, sizeof(void*), int_cmp);
I want to sort the ptrs to ascertain whether there are any duplicates, irrespective of the type of thing the pointer is pointing to, so the qsort is a precursor to doing that.
my int_cmp()
is pretty standard, e.g.
int int_cmp(const void *a, const void *b)
{
const int *ia = (const int *)a; // casting pointer types
const int *ib = (const int *)b;
/* integer comparison: returns negative if b > a
and positive if a > b */
return *ia - *ib;
}
it seems to work in my unit-tests but is there some reason why considering a ptr as an int may cause problems for such a scenario that i may have overlooked?
回答1:
No, you're not right at all, unless you want to sort the pointers by address. The actual address rarely has any meaning though, so that's very unlikely.
For detecting duplicate pointers, you should just compare the pointers as such, that's well-defined.
I would probably go with a solution using uintptr_t
:
static int order_pointers(const void *pa, const void *pb)
{
const uintptr_t a = *(void **) pa, b = *(void **) pb;
return a < b ? -1 : a > b;
}
Haven't tested this, but something like that should work.
The conversion to uintptr_t
is necessary since you cannot validly compare random pointers. I quoth the C99 draft standard, §6.5.8.5:
When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object or incomplete types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values. All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P. In all other cases, the behavior is undefined.
I bolded the final sentence since that's what applies here.
回答2:
Providing you use comparison, not subtraction, you can stick with void pointers: the following worked for a simple test:
int int_cmp( const void *pa, const void *pb )
{
const void* a = *(void**)pa ;
const void* b = *(void**)pb ;
if( a < b ) return -1 ;
if( a > b ) return 1 ;
return 0 ;
}
来源:https://stackoverflow.com/questions/22863406/sorting-an-array-of-pointers