我是否认为将指针视为 int 以便对指针数组进行排序是可以的,例如
qsort(ptrs, n, sizeof(void*), int_cmp);
我想对 ptr 进行排序以确定是否存在重复项,无论指针指向的内容是什么类型,因此 qsort 是执行此操作的先驱。
我的int_cmp()
非常标准,例如
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;
}
它似乎在我的单元测试中起作用,但是是否有某种原因将 ptr 视为 int 可能会导致我可能忽略的这种情况出现问题?
最佳答案
不,你完全不对,除非你想要按地址对指针进行排序。但实际地址很少有任何意义,所以这种可能性很小。
为了检测重复的指针,您应该只比较指针,这是明确定义的。
我可能会选择使用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;
}
还没有测试过这个,但类似的东西应该可以工作。
转换为uintptr_t
是必要的,因为您无法有效地比较随机指针。我引用 C99 标准草案,§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.
我将最后一句加粗,因为这就是此处适用的内容。
关于c - 对指针数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22863406/