为什么C++中有些字符无法编辑?

Lợi*_*yễn 7 c++ string strcat

我正在尝试strcat用 C++ 编写自己的函数,但它有一些问题。
\n我的输入是两个字符c和,我的函数将返回一个指向与 相连的a字符的字符指针。ca

\n

例如,
\n输入:\'abc\' \'xyz\'
\n预期输出:\'xyzabc\'
\n我的函数的输出:\'xyza@\xe2\x96\xb2\xe2\x88\xa9\'

\n

我的函数返回一些与我的输入不同的特殊字符。

\n

我调试了我的函数并发现:

\n
    \n
  • 当 时i=0destination[3]= source[0]=\'a\'
  • \n
  • 但当i=1, destination[8]= source[1]=\'b\'
  • \n
  • i=2, destination[9]= source[2]=\'c\'
  • \n
  • 最后,destination[10]=\'\\0\'
  • \n
\n
#include<iostream>\n#include<string.h>\nusing namespace std;\n\nchar* mystrcat ( char * destination, const char *source){\n    for (int i=0; i<strlen(source); i++) {\n        destination[strlen(destination)+i] = source[i];\n    }\n    destination[strlen(destination)+strlen(source)]=\'\\0\';\n    return destination;\n}\n\nint main() {\n    char c[100];\n    cin.getline(c, 99);\n    char a[100];\n    cin.getline(a,99);\n\n    mystrcat(a,c);\n    cout<<a;\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

Mur*_*nik 5

strlen返回从指针到它遇到的第一个指针的长度\0。在这里,在循环期间,您覆盖指针中的该字符destination,因此后续调用strlen将返回长度到内存中恰好保存该字符的某个随机点。

strlen一种简单的解决方法是在开始修改字符串之前提取结果:

char* mystrcat (char *destination, const char *source) {
    int destLen = strlen(destination);
    int srcLen = strlen(source);
    for (int i = 0; i < srcLen; i++) {
        destination[destLen + i] = source[i];
    }
    destination[destLen + srcLen] = '\0';
    return destination;
}
Run Code Online (Sandbox Code Playgroud)

  • @Chris你说得很好。“未定义行为”的重要性在于它比仅仅返回随机长度提供更多的自由度。如果幸运的话,它可能会使程序崩溃。如果你运气不好的话,你可能会发现[恶魔从你的鼻子里飞出来](http://www.catb.org/jargon/html/N/nasal-demons.html)。 (2认同)