使用strcat追加字符数组不起作用

ano*_*mys 2 c c++ buffer-overflow string-literals strcat

有人可以告诉我这段代码有什么问题吗???

char sms[] = "gr8";  
strcat (sms, " & :)");
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 14

sms是一个大小为4 1的数组.并且你附加了更多的字符文字,这些文字在数组之外,因为数组可以容纳4已被占用的最大字符数g, r, 8, \0.

顺便问一下,为什么4呢?答:因为最后有一个空字符!

如果你提到如下所示的数组大小,那么你的代码是有效且定义良好的.

char sms[10] = "gr8";  //ensure that size of the array is 10
                       //so it can be appended few chars later.
strcat (sms, " & :)");
Run Code Online (Sandbox Code Playgroud)

但是C++为您提供了更好的解决方案:std::string用作:

#include <string>  //must

std::string sms = "gr8";
sms += " & :)"; //string concatenation - easy and cute!
Run Code Online (Sandbox Code Playgroud)


Bo *_*son 8

是的,额外的角色没有空间.sms[]仅分配足够的空间来存储初始化的字符串.

使用C++,更好的解决方案是:

std::string sms = "gr8";
sms += " & :)";
Run Code Online (Sandbox Code Playgroud)