首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >bsearch()返回(0),导致分段错误

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

Stack Overflow用户
提问于 2015-01-07 14:20:56
回答 1查看 245关注 0票数 0

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

代码语言:javascript
复制
#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);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-07 14:23:07

在您的代码中,在else部分

代码语言:javascript
复制
if( item != NULL ) 
   {
      printf("Found item = %d\n", *item);
   }
   else 
   {
      printf("Item = %d could not be found\n", *item);
   }

即使itemNULL,您也取消了*item。请不要这样做。

为了解决保持信息输出消息完整的问题,也许您可以使用

代码语言:javascript
复制
printf(" Any item with related key value %d could not be found\n", key);

itemNULL时。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27821509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档