Hail! Wise and Glorious Gods of C Coding.

I have written a little function to search an array and it is cousing the program to hang after I enter the search criteria,It should should the array for a match and then return the whole string it was found in.

There is no error msg, and it compiles, I am using Dev-C. A pop-up juct comes and say's "the Program has stopped working, Windows is checking for a solution"

Would someone take a look and tell me where I have gone wrong and then give me a push in the right direction.

MyFunction

char find() { 

  int ctr;
  char search[50];
  int found;
  printf("search for");
  fflush(stdin);
  scanf("%s",&search);
  for(ctr=0; ctr<50;ctr++);
  {
      if(search[ctr] == array[8][ctr])
      {
            found=1;
      }
   }
      printf("%s",found);
      printf("\n\n%s",array[8][ctr]);
      if(found){
            for(ctr=0; ctr<50;ctr++) {
                printf("%s",array[8][ctr]);
            }
      }
  }       

MyData
in
char array[8][50] /*I believe thats whats in there, when I print printf("\n\n%s",array[n]); from my main this is what I get */

Lord Dunsmore?is married to?Lady Emily 
Miss Secrest?called?the Inspector 
The gardener?is married to?the maid 
Poison?can be procured by?a blood relative 
Mr. Mason?visited?at 3:00 P.M.

Recommended Answers

All 2 Replies

>> if(search[ctr] == array[8][ctr])

lines 14 and 23: you are using the wrong index (8) into array. Valid index numbers are 0, 1. 2, ... 7. The number 8 is beyond the bounds of the array.

line 16: add break to stop the loop

Besides the index of 8 being out of bounds, you have hard coded the value 8 so even if you were to change it to 7 or another valid index it would only check one of the strings in your array. You need a for loop to go through all strings in your array.

The check that you are doing to set found=1 is only for a single character and not an entire string. The character also has to be at the exact same position for both strings. You should use the function strstr(array, search) instead.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.