Answer the question
In order to leave comments, you need to log in
How to remove garbage from char array?
It is necessary to make the intersection of two signed arrays. By and large, everything works, but at the end it always displays a few incomprehensible characters. The array is being created correctly. I can't figure out what's wrong. Here is the method code:
String String::cross(const String& other)
{
size_t size;
size_t len1 = strlen(this->string_);
size_t len2 = strlen(other.string_);
if (len1 > len2)
{
size = len1;
}
else
{
size = len2;
}
size_t counter = 0;
for (size_t i = 0; i < size; i++)
{
if (this->string_[i] == other.string_[i])
{
counter++;
}
}
char* result = new char[counter+1];
for (size_t i = 0; i < size; i++)
{
if (this->string_[i] == other.string_[i])
{
result[i] = this->string_[i];
}
else
{
result[i] = '_';
}
}
return result;
}
Enter your string : hello
Enter your string : hola
h_l__¤¤
Answer the question
In order to leave comments, you need to log in
What is your intersection operation?
The first problem is that you are taking the maximum length of two strings in size
and then looping up to size on both strings. But there is simply no shorter line there - you are not accessing your memory.
You need to check if both strings exist at index i before comparing them.
The second problem is that you create result exactly the size of the number of matches, and write there in a loop up to size. Those. if you have no matches at all, then the result array will be empty, but you can write at least the 10000th element there if the lines are long enough.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question