c - Sorting an array of pointers -
am right in thinking fine treat pointer int purposes of sorting array of pointers, e.g.
qsort(ptrs, n, sizeof(void*), int_cmp);
i want sort ptrs ascertain whether there duplicates, irrespective of type of thing pointer pointing to, qsort precursor doing that.
my int_cmp()
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 > , positive if > b */ return *ia - *ib; }
it seems work in unit-tests there reason why considering ptr int may cause problems such scenario may have overlooked?
no, you're not right @ all, unless want sort pointers address. actual address has meaning though, that's unlikely.
for detecting duplicate pointers, should compare pointers such, that's well-defined.
i go solution using uintptr_t
:
static int order_pointers(const void *pa, const void *pb) { const uintptr_t = *(void **) pa, b = *(void **) pb; return < b ? -1 : > b; }
haven't tested this, should work.
the conversion uintptr_t
necessary since cannot validly compare random pointers. quoth c99 draft standard, §6.5.8.5:
when 2 pointers compared, result depends on relative locations in address space of objects pointed to. if 2 pointers object or incomplete types both point same object, or both point 1 past last element of same array object, compare equal. if objects pointed members of same aggregate object, pointers structure members declared later compare greater pointers members declared earlier in structure, , pointers array elements larger subscript values compare greater pointers elements of same array lower subscript values. pointers members of same union object compare equal. if expression p points element of array object , expression q points last element of same array object, pointer expression q+1 compares greater p. in other cases, behavior undefined.
i bolded final sentence since that's applies here.
Comments
Post a Comment