What I know (or just good at guessing at) doesn't matter.
What you need to develop are the skills to be able to write and debug your own code.
What I know (or just good at guessing at) doesn't matter.
What you need to develop are the skills to be able to write and debug your own code.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Rectification of the flaws here means implementing a correct algorithm. You need to do it yourself. Salem's suggestion of writing simple tests is a good one: I actually implemented your program myself, with a dozen test cases, two of which revealed bugs in my implementation (with empty strings and excessively long strings that could not fit into the output buffer: but do not implement the output buffer thing until you get the basic matching right).Originally Posted by emerald123
I already told you: your algorithm is wrong because it does not try to match the needle with the current substring of haystack from the start of the needle.Originally Posted by emerald123
Consider searching for "bc" in "abbc". The simple algorithm that I briefly outlined in post #8 will start by comparing 'b' from the needle with 'a' from the haystack. Not equal, so it then compares 'b' from the needle with the first 'b' from the haystack. Equal, so it goes into an inner loop and compares 'c' from the needle with the second 'b' from the haystack, saving the position of the outer loop at the first 'b' from the haystack. Not equal, so it ends the inner loop and starts over for the needle, moving to the next element in the haystack: it compares 'b' from the needle with the second 'b' from the haystack. Equal, so it goes back into the inner loop, comparing 'c' from the needle with 'c' from the haystack. At this point the end of the needle is reached, so there's a match.
Your algorithm, on the other hand, will do this: compare 'b' from the needle with 'a' from the haystack: not equal. Compare 'c' from the needle with the first 'b' from the haystack: not equal. Compare '\0' from the needle with the second 'b' from the haystack: not equal. Access the needle out of bounds and attempt to compare with 'c' from the haystack: undefined behaviour.
If you made any changes to the code that you posted in post #11, then you should post the updated code.Originally Posted by emerald123
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)