我决定尝试创建一个连接函数,因为 strcat 不适用于字符,仅适用于字符串。
\n\n#include <stdio.h>\n#include <string.h>\n\nchar concat(char a[], char b[]);\n\nint main ()\n{\n char *con = concat("hel", "lo");\n return(0);\n}\n\nchar concat(char a[], char b[]){\n int lena = strlen(a);\n int lenb = strlen(b);\n char con[lena+lenb];\n con[0] = a;\n con[lena] = b;\n printf("%s", con);\n return con;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n此代码打印“\xc3\x83\xe2\x80\xa6\xc3\x83\xc3\x86”。不确定我哪里出错了?
\n\n谢谢
\n首先,您不应该返回对临时的引用
char con[lena+lenb];
Run Code Online (Sandbox Code Playgroud)
(请注意,您得到的垃圾并不是来自于此,因为您在函数中进行了打印)
其次,您没有分配足够的内存:应该是(第一个问题已解决):
char *con = malloc(lena+lenb+1);
Run Code Online (Sandbox Code Playgroud)
然后无论如何使用 strcpy/strcat ,它更快,并且你的原始代码没有做任何有用的事情(将字符与字符数组混合并且数组的大小目前未知:这就是你的垃圾的原因得到):
strcpy(con,a);
strcat(con,b);
Run Code Online (Sandbox Code Playgroud)
或者正如一些人所说的那样,它们是不安全的函数,并且由于我们知道输入的大小,我们可以编写:
memcpy(con,a,lena);
memcpy(con+lena,b,lenb+1);
Run Code Online (Sandbox Code Playgroud)
另外:原型concat确实是错误的。它应该是:
char *concat(const char *a, const char *b){
Run Code Online (Sandbox Code Playgroud)
(因为它返回字符上的指针而不是字符。并且参数应该是常量指针,这样您就可以将函数与任何字符串一起使用)
就完成了(完成后不要忘记释放字符串)
修复代码(经过测试,令人惊讶地返回hello,可能是因为它编译时没有错误gcc -Wall -Wwrite-strings -Werror。我的建议:打开警告并阅读它们。这样你就可以解决 80% 的问题):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *concat(const char *a, const char *b);
int main ()
{
char *con = concat("hel", "lo");
printf("%s\n",con);
return(0);
}
char *concat(const char *a, const char *b){
int lena = strlen(a);
int lenb = strlen(b);
char *con = malloc(lena+lenb+1);
// copy & concat (including string termination)
memcpy(con,a,lena);
memcpy(con+lena,b,lenb+1);
return con;
}
Run Code Online (Sandbox Code Playgroud)