Please can someone help me and show me where i am going wrong ?
The code below is not an assignment or homework
it is something i am tryigng to do for work.

The code scans a text file ( attached ) and stores 10 x 5 digit ints into an array
It then uses a recursive call to search the array for a with a number from stdin

when i run the code and enter a number to search it crashes

#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>

int main(){

  int numberstore [10];

  int num ;

     int i =0;

     int m,c,l,u,b,n,a;

    FILE *inputfile;

    inputfile= fopen("numbers.txt","r");

    if (inputfile == NULL)
        {
    printf("error! opening file\n");

    exit(0);
        }


while (fscanf(inputfile, "%d", &num) > 0) // scan the input file and store items in the array
{
numberstore[i] = num;

i++;

}

fclose(inputfile);

 printf("Enter the number to be searched:");

    scanf("%d",&m);

    l=0,u=n-1;

    c=binary(a,n,m,l,u);

    if(c==0)

         printf("Number is not found.");
    else

         printf("%d Number is found.",c);


    return 0;
 }




int binary(int a[],int n,int m,int l,int u){

     int mid,c=0;

     if(l<=u){
          mid=(l+u)/2;
          if(m==a[mid]){
              c=1;
          }
          else if(m<a[mid]){
              return binary(a,n,m,l,mid-1);
          }
          else
              return binary(a,n,m,mid+1,u);
     }
     else
       return c;
}
Attachments
12345
45678
91011
44444
55555
98756
33333
22222
11111
4242

What are you compiling this with? The function binary is expecting an int* as the first parameter, but you're passing it an int. This is very bad news, and your compiler really should have said something about it.

I see also that you're using unknown, basically random values for a, n, u. If you're going to use these variables, shouldn't you be giving them some value?

Edited 1 Year Ago by Moschops

Hi
I am using the GNU compiler
So should I intialise line 43
C* = binary
Also Shall I set a, n, u =0;
At the start
Thanks

You need to think about what you're doing.

a is an int. You're trying to use it as if it were a pointer. An int is not the same thing as a pointer.

This article has been dead for over six months. Start a new discussion instead.