-1

He, I need some help because of I can't figure out what it shows me strange numbers in the output I mean. It works for instance name_1 + name_2 but I get extra some characters Anna+Mark&@#$@@ just for example.

class String
{
private:
    char* str;
    int len;
    static int num_strings;
    static const int CINLIM = 80;
};

String& operator+(String& st, String& st2)
{
    char* napis = new char[st.len + st2.len]; 

    int i;
    for (i=0; st.str[i] != '\0'; i++)
    {
        napis[i] = st.str[i];
    }
    napis[i] = '+';

    int static j = i+1;
    for (int a = 0; st2.str[a] != '\0'; a++,j++)
    {
        napis[j] = st2.str[a];
    }
    st2.str[j] = '\0';
    for (int i = 0; i < j; i++)
    {
        cout << napis[i] << std::endl;
    }
    delete st.str;
    strcpy(st.str, napis);
    return st;
}
001
  • 13,291
  • 5
  • 35
  • 66
Marian
  • 1
  • 3
    Why is `j` static? – Brian61354270 Mar 19 '20 at 19:17
  • 3
    You aren't allocating room for the `'\0'` or the `'+'`. `char* napis = new char[st.len + st2.len + 2];` – 001 Mar 19 '20 at 19:17
  • 2
    Also, you `delete st.str` then try to copy a string into it. You need to reallocate space for the new string before copying into it: `st.str = new char[strlen(napis) + 1];` – 001 Mar 19 '20 at 19:20
  • 2
    `delete` should be `delete[]` here. And you are using `st.str` *immediately* after `delete`ing it. You might have meant to write `st.str = napis` there. – François Andrieux Mar 19 '20 at 19:28
  • 1
    @JohnnyMopp They already allocated a new array, it's `napis`. `st.str = napis` is what they meant here. – François Andrieux Mar 19 '20 at 19:29
  • Thanks for help. I was trying to many things because I I hadn't had any idea how get it working. – Marian Mar 19 '20 at 19:31
  • @FrançoisAndrieux Good point. – 001 Mar 19 '20 at 19:31
  • Does this answer your question? [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) Signatire for `operator+` is incorrect – Richard Critten Mar 19 '20 at 19:35

1 Answers1

0

You have multiple orpblems in your code, but the main one:

int static j = i+1;

The static function variable is initialized only once (the first time). I guess this is not what you actually ment, and this must be the reason of extra characters (you just use the value of j from the previous invocation of the function, and this value always grows). You don't need the variable to be static.

Some more problems: Why don't you use std::string? Even if you are studying C-style string management, you definitely need to manage allocation/deallocation in ctors. Consider other problems reported in the comments to your question.

Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40