我决定尝试创建一个连接函数,因为 strcat 不适用于字符,只能用于字符串。
#include <stdio.h>
#include <string.h>
char concat(char a[], char b[]);
int main ()
{
char *con = concat("hel", "lo");
return(0);
}
char concat(char a[], char b[]){
int lena = strlen(a);
int lenb = strlen(b);
char con[lena+lenb];
con[0] = a;
con[lena] = b;
printf("%s", con);
return con;
}
这段代码打印出“A…A”。不确定哪里出错了?
谢谢
最佳答案
首先,你不应该返回临时引用
char con[lena+lenb];
(请注意,您得到的垃圾并非来自于此,因为您在 函数中打印)
其次,你没有分配足够的内存:应该是(第一个问题已解决)
char *con = malloc(lena+lenb+1);
然后无论如何使用 strcpy/strcat,它更快,并且您的原始代码没有做任何有用的事情(将字符与字符数组混合,并且此时不知道数组的大小:那是 你得到垃圾的原因):
strcpy(con,a);
strcat(con,b);
或者正如一些人所说的那样,它们是不安全的函数,并且由于我们知道输入的大小,我们可以这样写:
memcpy(con,a,lena);
memcpy(con+lena,b,lenb+1);
另外:concat
的原型(prototype)确实是错误的。应该是:
char *concat(const char *a, const char *b){
(因为它返回一个 char 指针而不是一个 char。而且参数应该是常量指针,这样你就可以将你的函数与任何字符串一起使用)
你就完成了(不要忘记在完成后释放字符串)
固定代码(经过测试,令人惊讶地返回 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;
}
关于c - 如何在c中连接两个char数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40195731/