有人能告诉我这段代码有什么问题吗???
char sms[] = "gr8";
strcat (sms, " & :)");
有人能告诉我这段代码有什么问题吗???
char sms[] = "gr8";
strcat (sms, " & :)");
sms
4
是一个大小为1的数组。而且您正在附加更多的字符文字,这些文字超出了数组的范围,因为数组可以容纳4
已被g, r, 8, \0
.
1. 顺便问一下,为什么正好是 4?答:因为最后有一个空字符!
如果您提到数组的大小,如下所示,那么您的代码是有效且定义明确的。
char sms[10] = "gr8"; //ensure that size of the array is 10
//so it can be appended few chars later.
strcat (sms, " & :)");
但随后 C++ 为您提供了更好的解决方案:std::string
用作:
#include <string> //must
std::string sms = "gr8";
sms += " & :)"; //string concatenation - easy and cute!
是的,没有多余的字符空间。sms[]
只分配足够的空间来存储它初始化的字符串。
使用 C++,更好的解决方案是:
std::string sms = "gr8";
sms += " & :)";
您正在将数据复制到未分配的内存中。
当你这样做时:char sms[] = "gr8";
你创建一个有 4 个字符的 char 数组,“gr8”加上字符串末尾的 0 字符。
然后,您尝试通过strcat
调用将多余的字符复制到数组中,超出数组的末尾。这会导致未定义的行为,这意味着会发生不可预知的事情(程序可能会崩溃,或者您可能会看到奇怪的输出)。
要解决此问题,请确保要将字符复制到的数组足够大以包含所有字符,并且不要忘记末尾的 0 字符。
在 C 中,数组不会自动增长。
sms
有一个特定的长度(4,在这种情况下 - 三个字母和终止 NULL)。当您调用 时strcat
,您正试图将字符附加到该数组超过其长度。
这是未定义的行为,会破坏您的程序。
相反,如果你分配了一个足够大的数组来包含两个字符串,你会没事的:
char sms[9] = "gr8";
strcat (sms, " & :)");
C++ 对数组有(基本上)与 C 相同的限制。但是,它提供了更高级别的功能,因此您不必经常处理数组,例如std::string
:
#include <string>
// ...
std::string sms = "gr8";
sms += " & :)";
这样做更好的原因是您不必提前知道字符串的确切长度。C++ 将为您增加内存中的底层存储。
字符数组的缓冲区溢出,然后在某处崩溃!
您的短信缓冲区只有 4 个字符长。strcat 将在其末尾再复制 5 个字符并破坏堆栈。