【问题标题】:C++ program crashing (array and 2 pointer binsearch function)C++ 程序崩溃(数组和 2 指针 binsearch 函数)
【发布时间】:2012-10-20 10:00:10
【问题描述】:

当我运行这个程序并输入一个值来搜索程序崩溃时(exe 已经停止工作,关闭程序)。输入值 65 时,出现无限循环 Number not found Enter a value to search (-1 to quit):

代码如下:

#include <iostream>
using namespace std;

void Search(int[], int * , int * );

int main()
{

  int i,KEY,num, array[] = {98,87,76,65,54};


  for(i=0;i<5;i++)
    cout << array[i] << " ";

  Search(array, &KEY, &num);

  cout << endl;
  system("pause");
  return 0;
}

void Search(int arr[5], int * current, int * numel)
{

  int low, high,search,N;

  cout << "\nWhat Number would you like to search for? (-1 to quit) : ";
  cin >> search;

  while(search!=-1)
  {
    low=0;
    high=N-1;
    while(low<=high)
    {
      *current=(low+high)/2;
      if (search > arr[*current])
        low=*current+1;
      else if(search<arr[*current])
        high=*current-1;
      else
        break;
    }
    if(arr[*current]==search)
      cout << "Number found at index " << *current << endl;
    else
      cout << "Number not found." << endl;
    cout << "Enter a value to search (-1 to quit) :";
  }
  return;
}

【问题讨论】:

  • 我的问题是为什么我的代码会失败/崩溃?
  • 我建议您自己对崩溃进行一些研究。首先使用调试器或插入输出语句来查找崩溃发生的位置。然后从那里向后工作,试图找出问题所在。
  • 谢谢,似乎数组值没有被传递给函数和/或如果找不到值,则循环永远不会结束。
  • 啊!!数组不是从低到高的顺序。
  • 感谢指导,程序运行良好。

标签: c++ arrays search pointers binary


【解决方案1】:

N 没有初始化,所以谁知道这个语句是什么:

high=N-1;

会吗?

【讨论】:

  • 更改了 int 低、高、搜索、N; to int low, high,search,N=5;
  • 那有什么改变吗?该代码可能还有其他一些问题。使用调试器单步执行或抛出一些 printf() 语句(如果您出于某种原因不想使用调试器)可能会提供一些见解。
  • 停止了崩溃,但现在我每次搜索都有无限循环。
【解决方案2】:

首先,如果要查找的数字不在数组中,则无法退出 Search 中的主循环。

那么你在 high 被赋予任何价值之前就使用它。

可能还有其他问题。您在开发过程中如何对其进行测试?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2018-02-22
    • 1970-01-01
    相关资源
    最近更新 更多