在 C 中将 void* 转换为 char*

标签 c pointers casting binary-search

我必须为任何数据类型编写一个抽象的二进制搜索函数,并将比较函数作为参数。我不知道如何处理 void,因为不可能使用指针运算。然后我看到了标准的 qsort 函数并照做了。问题是当发生从 void*char* 的转换时发生了什么?为什么有效?

void *bin_srch(void *a, size_t n, size_t bs, void *x, int (*cmp)(const void *a, const void *b))
{
    size_t f = 0, l = n;

    if(!n) return NULL;

    while (f < l)
    {
        size_t m = f/2 + l/2;
        char *mid = (char*)a + m*bs;

        if (cmp(x, mid) <= 0)
            l = m;
        else
            f = m + 1;
    }

    char *t = (char*)a + l*bs;

    if (!cmp(t, x))
        return t;
    else
        return NULL;
}

最佳答案

它有效,因为 char * 可以别名任何其他类型。

引自 C11,第 6.3.2.3 章

[....] When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object.

使用此属性,转换为 char * 可以使用(转换的)指针作为操作数来执行指针算术。

如同一规范中所述(我强调),第 6.5.6/p2 章

For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type. (Incrementing is equivalent to adding 1.)

和,p3

For subtraction, one of the following shall hold:

  • both operands have arithmetic type;

  • both operands are pointers to qualified or unqualified versions of compatible complete object types; or

  • the left operand is a pointer to a complete object type and the right operand has integer type.

需要指针操作数是指向完整类型的指针,void 不是,char 是。

最后,引用章节 §6.2.5/p19

The void type comprises an empty set of values; it is an incomplete object type that cannot be completed.

关于在 C 中将 void* 转换为 char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42700655/

相关文章:

c - c中的种子随机数

c - 为什么在使用 "Quotes"创建 char* 时不需要释放内存

c++ - 我收到一个看起来应该是 "just work."的程序的奇怪错误

c - 将 `int_least8_t` 转换为 `char` 时如何发出警告?

c - 变量值不变

c - PTRACE_SYSEMU 和 PTRACE_SYSEMU_SINGLESTEP 未在 x64 或 x86 上定义?

C++ 基类型到指针的转换

java - 请解释使用显式转换为对象的输出

java - 创建通过反射获得的对象集合

c - 了解 C 程序