我被要求编写一个具有一些特定条件的二分搜索程序。我必须传递下限、上限、数组指针和搜索元素。我写的程序给了我警告。我无法纠正程序中的错误。请指出我哪里错了。
#include <stdio.h>
int BinarySearch(int , int , int *, int );
int main()
{
int n, i, a[20], h, l, x, r=0;
int *p;
printf("Enter the number of elements:\n");
scanf("%d",&n);
printf("Enter the elements:\n");
for( i=0 ; i<n ; i++)
{
scanf("%d",&a[i]);
}
p = &a[0];
printf("Enter the element to be searched:\n");
scanf("%d", &x);
l = 0;
h = n-1;
r = BinarySearch(l, h, p, x);
if(r == 1)
printf("The element %d is found in position %d", x, i);
else
printf("The element %d is not present in the array", x);
return 0;
}
int BinarySearch(int l, int h, int *p, int x)
{
int mid, a[20], f =0;
*p = a[0];
mid = ( l + h )/2;
while( l <= h )
{
if( a[mid] == x )
{
f=1;
break;
}
else if( a[mid] > x )
{
h = mid-1;
}
else if( a[mid] < x )
{
l = mid+1;
}
}
if(f == 1)
{return 1;}
else
{return -1;}
}
编译时收到此警告。
main.c|38|warning: 'a[0]' is used uninitialized in this function [-Wuninitialized]|
当我删除行 *p = a[0];
时,我收到以下错误消息:
main.c|43|warning: 'a[mid]' may be used uninitialized in this function [-Wmaybe-uninitialized]|
main.c|48|warning: 'a[mid]' may be used uninitialized in this function [-Wmaybe-uninitialized]|
main.c|52|warning: 'a[mid]' may be used uninitialized in this function [-Wmaybe-uninitialized]|
当我运行程序时,程序会获取搜索元素的值并在一段时间后终止。控制权不转移到二分查找函数。
最佳答案
原始数组在 main() 中定义,单独的数组在 BinarySearch() 中定义。指针 p 被分配为指向 main 中定义的数组。
p = &a[0];
指针p传入BinarySearch(),然后赋值
*p = a[0]
实际上是将指针内容更改为 BinarySearch() 中定义的新数组的第一个元素。新数组未初始化,因此会出现相应的编译器警告。
关于c - C 中指针的二分查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45209776/