I wanted to start simple with a linear search in the helper.c function:

bool search(int value, int values[], int n)
   // TODO: implement a searching algorithm
for (int i = 0; value < n; i++)
    if ( value == values[i])
    return true;
return false;

I compile find.c without error. Then, when I do:

./generate 1000 50 | ./find 128

I receive multiple lines of blank haystacks, with a claim that I found the needle.:

haystack[994] = 
haystack[995] = 
haystack[996] = 
haystack[997] = 
haystack[998] = 
haystack[999] = 
haystack[1000] = 

Found needle in haystack!

According to the instructions, I should not find a needle in this case. Also, I assume I should not be printing out all these haystacks. What am I doing wrong?


You may not be doing anything wrong. As I recall (it's been more than a year), when you run the program (manually or with input from generate), it will always print out a prompt for "haystack[i]= ". When manually run, it will wait for you to input a number. When run against generate, it will print out all of the prompts without waiting, as you are seeing. If generate is spitting out a thousand numbers, it will print what you are seeing.

The important thing is that it is saying Found needle only once if it is there and needle not found if it is not there. Have you run it against check50? If check50 is happy, just smile and move on to coding for a binary search. ;-)

[EDIT: added comments] As for returning true, there's at least one problem - the for loop test condition. It checks for value < n. I'm surprised that this doesn't generate an infinite loop or a seg fault. With this test, it will either fail immediately, or will run past the end of the array because value and n don't change (effectively always true or always false). The only thing that might change this is if random data happens to equal content of value at some point, returning a true. Otherwise, it is more likely to seg fault when it exceeds memory bounds.

Perhaps you meant to have i < n? It's also possible that the code that you're compiling doesn't match what was posted, which could have entirely different results.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |
  • Unfortunately, it is finding the needle even when it should not. Why is that the case? – Haim May 7 '17 at 2:12
  • See my edited answer. – Cliff B May 7 '17 at 3:03
  • Great - that was the problem! – Haim May 7 '17 at 14:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .