D
D
Danil Vaskevich2021-06-01 13:11:24
C++ / C#
Danil Vaskevich, 2021-06-01 13:11:24

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;
}


and here is the output:
Enter your string : hello

Enter your string : hola
h_l__¤¤


Help me please.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Wataru, 2021-06-01
@wataru

What is your intersection operation?
The first problem is that you are taking the maximum length of two strings in sizeand 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 question

Ask a Question

731 491 924 answers to any question