c - 对指针数组进行排序

标签 c sorting pointers

我是否认为将指针视为 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/

相关文章:

C 字符串在超过 7 个字符时表现异常

c - TI MSP430 中断源

javascript - JS 中从分数到排行榜排序字典

c - 为什么文件数据不保存到结构中?

c++ - 可移植标记指针

python - 读取管道(C/C++),没有错误,但不是所有数据

c - 添加到排序的链表

jquery - 使用 jQuery DataTables 时禁用第一列的自动排序

Python确保对象出现在列表的末尾

c++ - 为什么断点显示我的数组的第二个值是一个很大的数字?额外学分工作