函数memchr(从其名称而来)在字符数组中搜索字符。您不能使用它来查找int 类型的对象,因为该函数不处理此类对象。
你应该自己写一个合适的函数。
例如,它可以如下面的演示程序所示如下所示
#include <stdio.h>
int * find( const int *a, size_t n, int value )
{
const int *first = a;
while ( first != a + n && *first != value ) ++ first;
return first == a + n ? NULL : ( int * )first;
}
int main(void)
{
int a[4][2] =
{
{ 1, 2 },
{ 3, 0 },
{ 4, 5 },
{ 0, 6 }
};
const size_t M = sizeof( a ) / sizeof( *a );
const size_t N = sizeof( *a ) / sizeof( **a );
int value = 0;
int *p = ( int * )a;
for ( ; ( p = find( p, M * N - ( p - ( int * )a ), value ) ) != NULL; ++p )
{
size_t m = ( p - ( int * )a ) / N;
size_t n = ( p - ( int * )a ) % N;
printf( "a[%zu][%zu] is equal to %d\n", m, n, value );
}
return 0;
}
程序输出是
a[1][1] is equal to 0
a[3][0] is equal to 0
使用此函数,您可以在任何多维整数数组中找到任何值。
该函数只是将多维数组解释为一维数组并返回指向搜索元素的指针。您可以使用此指针计算此元素的“坐标”,并了解数组的维度,如演示程序中二维数组所示。
通过类比标准 C 函数bsearch,您可以编写一个通用搜索函数来处理任何整数类型的数组。
例如
#include <stdio.h>
#include <string.h>
void * find( const void *value, const void *base, size_t nmemb, size_t size )
{
const unsigned char *first = base;
while ( first != ( const unsigned char * )base + nmemb * size &&
memcmp( first, value, size ) != 0 ) first += size;
return first == ( const unsigned char * )base + nmemb * size ? NULL : ( void * )first;
}
int main(void)
{
int a[4][2] =
{
{ 1, 2 },
{ 3, 0 },
{ 4, 5 },
{ 0, 6 }
};
const size_t M = sizeof( a ) / sizeof( *a );
const size_t N = sizeof( *a ) / sizeof( **a );
int value = 0;
for ( int *p = ( int * )a; ( p = find( &value, p, M * N - ( p - ( int * )a ), sizeof( int ) ) ) != NULL; ++p )
{
size_t m = ( p - ( int * )a ) / N;
size_t n = ( p - ( int * )a ) % N;
printf( "a[%zu][%zu] is equal to %d\n", m, n, value );
}
return 0;
}
程序输出同上图
a[1][1] is equal to 0
a[3][0] is equal to 0
在 C++ 中,您可以使用相同的方法将多维数组重新解释为一维数组,并应用标头 <algorithm> 中声明的标准算法 std::find。