如何解决需要帮助理解 C
我无法理解 C 中 bsearch 函数的 this 实现中的第一行代码。我理解搜索算法本身并且我已经尝试过这个函数以很好地掌握它,但我仍然没有得到什么
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 %p\n",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 %p\n",( 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 )
来访问传递数组的元素。>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。