考虑以下代码:
void fun (string &str1, string &str2)
{
const char* cstr;
....
if(strlen(cstr = (str1+str2).c_str()) < 15)
{
// here cstr used
}
}
条件本身工作正常,但在 if 条件体 cstr
中包含垃圾。为什么?
最佳答案
在这个表达式中:
cstr = (str1+str2).c_str()
您正在使用指向临时 字符串str1 + str2
的指针。这个临时变量在表达式的末尾终止,因此当您尝试从 if-body 中的 cstr
读取时,您会遇到未定义的行为。
关于C++ 字符串到 C 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61664817/