【问题标题】:bsearch() returns (nil), causes segmentation faultbsearch() 返回 (nil),导致分段错误
【发布时间】:2015-01-07 14:20:56
【问题描述】:

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);
}

【问题讨论】:

  • C 中没有 nil。不过,NULL 实际上是一回事。
  • 在 C 中你不应该转换 void *。这样做实际上可以隐藏您忘记声明您正在调用的函数(或忘记包含正确的头文件)的问题。在 C 中,所有指针都可以隐式转换为void*,反之亦然。那么只有在取消引用这样的指针时才需要显式转换 void*
  • @JoachimPileborg,s/所有指针/所有对象指针/g

标签: c pointers segmentation-fault bsearch


【解决方案1】:

在您的代码中,在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

【讨论】:

  • printf("Item = %d could not be found\n", key); 将是安全的解决方法。
  • @PaulRoub 确实如此。也许printf(" Any item with related key value %d could not be found\n", key); 也可以。 :-)
猜你喜欢
  • 1970-01-01
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 2021-08-02
  • 2015-11-15
  • 1970-01-01
  • 2018-06-17
  • 1970-01-01
相关资源
最近更新 更多