Junk after C++ string when returned

前端 未结 2 1070
挽巷
挽巷 2021-01-28 07:49

I\'ve just finished C++ The Complete Reference and I\'m creating a few test classes to learn the language better. The first class I\'ve made mimics the Java StringBuilder class

2条回答
  •  野性不改
    2021-01-28 08:11

    You need to null terminate the string. That null character tells the computer when when string ends.

    char * copy = new char[ length + 1];
    for(int i = 0; i < length; ++i) copy[i] = stringArray[i];
    copy[length] = 0; //null terminate it
    

    Just a few things. Declare the int variable in the tighest scope possible for good practice. It is good practice so that unneeded scope wont' be populate, also easier on debugging and kepping track. And drop the 'register' keyword, let the compiler determine what needs to be optimized. Although the register keyword just hints, unless your code is really tight on performance, ignore stuff like that for now.

提交回复
热议问题