错误是返回局部数组变量的地址str
.它的范围在函数内concatStrings()
您声明的位置,一旦控制权从函数返回就无法访问。
要从外部访问它,您需要使用以下命令从堆中为字符串动态分配内存new
操作员。
char* concatStrings(char* s1, char* s2, char sep){
int s1Length = strlen(s1);
int sLength = s1Length + strlen(s2) + 2;
// +1 for sep and +1 \0 at end of string
char* str = new char[sLength];
strcpy (str, s1);
// Use strlen here instead of sizeof()
str [s1Length] = sep;
str [s1Length + 1] = '\0';
strcat (str, s2);
return str;
}
程序完成后,使用返回的字符串concatStrings
它应该确保通过调用来释放内存delete
char* str = concatStrings(s1, s2, sep);
// Do something
// Free up memory used by str
delete[] str;
这里必须使用delete[]而不是delete,否则会导致未定义的行为
我还编辑了concatStrings()
使用函数strlen
代替sizeof
更新:感谢您指出我们只需要执行 +2 而不是 +3,并确保需要在后面附加 '\0'str1
and sep
在调用之前strcat