我很难理解C中bsearch函数实现中的第一行代码。我理解搜索算法本身,我也试过使用这个函数来很好地掌握它,但我仍然不知道是什么
const char *base = (const char *) base0;
确实如此,为什么它被允许,为什么它必须是char,而不能是其他类型。当我使用相同的函数,但将类型转换为(const int*) base0;
,然后使用C Tutor来了解发生了什么时,我注意到变量p变成了无效内存的指针,但我不知道为什么会发生这种情况,也不知道为什么这个函数同时适用于字符串和整数。
在函数中,您需要在传递的数组中找到每个元素。但是,数组的类型未知。您只知道数组中每个元素的大小以及通过参数base0传递的数组的起始地址。类型为const void *
。。
要访问数组中的一个元素,您需要使用指针算术。但类型void是不完整类型。它的大小未知/因此,在具有指针算术的表达式中,不能使用(const(void*`类型的指针。
因此,本声明
const char *base = (const char *) base0;
介绍了const-char*类型的指针基,您可以使用它来访问数组的元素,如以下语句中所示
p = base + (lim >> 1) * size;
或者示例base + size
将指向阵列的第二个元素。
这是一个示范节目。
#include <stdio.h>
void f( const void *base, size_t nmemb, size_t size )
{
for ( size_t i = 0; i < nmemb; i++ )
{
const char *p = ( const char * )base;
printf( "The address of the %zu-th element is %pn",
i, ( const void *)( p + i * size ) );
}
}
int main(void)
{
int a[] = { 1, 2, 3 };
const size_t N = sizeof( a ) / sizeof( *a );
for ( size_t i = 0; i < N; i++ )
{
printf( "The address of the %zu-th element is %pn",
i, ( const void *)( a + i ) );
}
putchar( 'n' );
f( a, N, sizeof( int ) );
return 0;
}
程序输出可能看起来像
The address of the 0-th element is 0x7ffc45c6d4dc
The address of the 1-th element is 0x7ffc45c6d4e0
The address of the 2-th element is 0x7ffc45c6d4e4
The address of the 0-th element is 0x7ffc45c6d4dc
The address of the 1-th element is 0x7ffc45c6d4e0
The address of the 2-th element is 0x7ffc45c6d4e4
在main中,您可以使用表达式( a + i )
使用指针算术,因为在该表达式中,数组指示符隐式转换为类型int *
,而类型int
是一个完整的类型(其大小已知(。
但是,在函数f中,您不能使用表达式( base + i )
,因为指针的类型为const void *
,而类型void不是完整的类型(其大小未知(。
因此,将指针强制转换为类型const char *
,我们可以对该指针使用指针算术,但在这种情况下,我们需要使用表达式( p + i * size )
来访问传递数组的元素。