gpt4 book ai didi

在 C 中将 void* 转换为 char*

转载 作者:太空宇宙 更新时间:2023-11-04 01:20:58 27 4
gpt4 key购买 nike

我必须为任何数据类型编写一个抽象的二进制搜索函数,并将比较函数作为参数。我不知道如何处理 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com