Reputation: 3221
Hello this is a segment of my code of which i am trying to implement the Morris-Pratt algorithm. When i am comparing my variables if find that they dont match, this is because one of my variables "Temp" is geting extra characters added to the end of the array. here is my code...
// Calculate the next talbe
char test[searchLen];
for(int i = 0; i < searchLen; i++)
{
test[i] = fileContent[currPos+i];
}
cout << "SEARCHLEN: " << searchLen << endl;
cout << "TEST: " << '\t' << '\t' << test << endl;
cout << "SEARCH: " << '\t' << search << endl;
cout << strcmp(test,search) << endl << endl;
// Determine if a match is detected
if(strcmp(test,search)==0)
{
cout << "----------------------> Match detected at: " << currPos << endl;
}
currPos ++;
}
return numberOfComparisons;
}
The output looks like this...
SEARCHLEN: 8
TEST: athsoutg5?h
SEARCH: brilling
-1
As you can see the 5?H is not supposed to be there and is breaking my code.
Upvotes: 2
Views: 2033
Reputation: 16718
You need to add a null terminator.
char test[searchLen + 1];
test[searchLen] = '\0';
Upvotes: 6
Reputation: 5227
It does look like your string is not terminated with \0, maybe you forgot to copy it / put it in there?
Upvotes: 1