【发布时间】:2014-05-16 19:16:18
【问题描述】:
我是否认为可以将指针视为 int 以便对指针数组进行排序,例如
qsort(ptrs, n, sizeof(void*), int_cmp);
我想对 ptrs 进行排序以确定是否有任何重复项,而不管指针指向的事物的类型,所以 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 可能会导致我可能忽略的这种情况出现问题?
【问题讨论】:
-
不,您不能将指针视为
int。指针的大小可能与int的大小不同。还要记住,有许多类型的数据不能直接比较,也不能用于算术表达式(例如结构)。 -
只有
intptr_t和uintptr_t是保证能够保存指针的整数变量。 -
应该是
const int *ia = *(const int **)a; const int *ib = *(const int **)b; -
那么,当
int的数组而不是int *的数组时,你会怎么做? -
我的示例 cmp 函数用于整数数组:指针数组,例如qsort(ptrs, n, sizeof(void*), int_cmp); 使用
int_cmp表示指针数组。