繁体   English   中英

bsearch()返回(无),导致分段错误

[英]bsearch() returns (nil), causes segmentation fault

bserach()函数应该返回NULL,但是,当它无法在给定数组中找到键时,我得到(nil)。 怎么了

#include <stdio.h>
#include <stdlib.h>
int cmpfunc(const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}    
int values[] = { 5, 20, 29, 32, 63 };    
int main ()
{
   int *item;
   int key = 10;

   /* using bsearch() to find value 32 in the array */
   item = (int*) bsearch (&key, values, 5, sizeof (int), cmpfunc);
   if( item != NULL ) 
   {
      printf("Found item = %d\n", *item);
   }
   else 
   {
      printf("Item = %d could not be found\n", *item);
   }       
   return(0);
}

在您的代码中,在else部分

if( item != NULL ) 
   {
      printf("Found item = %d\n", *item);
   }
   else 
   {
      printf("Item = %d could not be found\n", *item);
   }

即使itemNULL ,您也要取消引用它[ *item ]。 请不要这样做。

要解决使信息输出消息完整的问题,也许您可​​以使用一些方法

printf(" Any item with related key value %d could not be found\n", key);

itemNULL

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM