c - C 中指针的二分查找

标签 c arrays function pointers binary-search

我被要求编写一个具有一些特定条件的二分搜索程序。我必须传递下限、上限、数组指针和搜索元素。我写的程序给了我警告。我无法纠正程序中的错误。请指出我哪里错了。

#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/

相关文章:

javascript - 提交表单时如何从多选中获取数组[AngularJS]

C 语言中可以使用 scanf() 来声明变量吗?

char ** nargv 为空但不知道为什么

c++ - 数组中是否也可以动态删除内存?

javascript - 将 excel 二维数组转换为包含列名的嵌套属性对象

javascript - 输入字符 Controller

子进程与父进程之间的通信

c - 对指向指针的指针使用 realloc() 时,指针值会发生变化

function - MySQLdump 因例程挂起

function - 为什么我收到此错误消息 “UnboundLocalError: local variable ' sigma_opt在分配前被引用”