简体   繁体   中英

gettinan error in the program warning: implicit declaration of function 'Binsearch' [-Wimplicit-function-declaration] res= Binsearch(arr,n-1,0,x);

#include <stdio.h>

//int Binsearch(int,int,int,int);

int main() {
    int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int res;
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 7;

    res = Binsearch(arr,n-1,0,x);
   
    (res == -1) ? printf("element not found") : printf("element found at index :%d", res);

    return 0;
}

int Binsearch(int arr[], int h, int l, int p) {
    int mid;
    if (h >= l) {
         mid = ((h - l) + l) / 2;
    
         if (arr[mid] == p)
           return mid;
    
         if (p > arr[mid])
           return Binsearch(arr, h, mid + 1, p);
       
         return Binsearch(arr, mid - 1, l, p);
    } 
    return -1;    
}

// getting error plzz this code

warning: implicit declaration of function 'Binsearch' [-Wimplicit-function-declaration]    res= Binsearch(arr,n-1,0,x);

In both C and C++ you have to declare or define functions before you call them. Since the call to Binsearch in main comes before its definition, you need a declaration of Binsearch in scope first.

It looks like you tried to provide one with the line

//int Binsearch(int,int,int,int);

but you commented it out, probably because it caused other errors. It was almost right, but the first parameter is not an int but an array of int . So it should be changed to

int Binsearch(int[],int,int,int);

When you omit a declaration, some compilers will provide an "implicit" one, basically a default assumption of the parameters and return type of the function. This default is almost always wrong, so a warning about an implicit declaration usually means your code will fail unless you fix it. See warning: implicit declaration of function for more info.


Your program has another bug:

     mid=((h-l)+l)/2;

That is the same as mid=h/2; which is not what you want. In particular at some point you call Binsearch() with h=8 and l=5 , which makes mid=4 . Since p > arr[mid] you call Binsearch(arr,h,mid+1, p); , and mid+1 == 5 again, so your program makes no progress, performs infinite recursion, and crashes.

Rethink the math and decide what that line should be instead.

For general advice on debugging small programs like this, seehttps://ericlippert.com/2014/03/05/how-to-debug-small-programs/ . In particular, using a debugger made it very easy for me to see where the program failed, and which values of h and l caused it. I suggest practicing using a debugger for yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM