如何将 char 连接到常量 char*?
我有一个函数连接两个常量 char* 并返回结果。我想做的是将 char 连接到常量 char* 例如
char *command = "nest";
char *halloween = join("hallowee", command[0]); //this gives an error
char *join(const char* s1, const char* s2)
{
char* result = malloc(strlen(s1) + strlen(s2) + 1);
if (result)
{
strcpy(result, s1);
strcat(result, s2);
}
return result;
}
I have a function that joins two constant char* and returns the result. What I want to do though is join a char to a constant char* eg
char *command = "nest";
char *halloween = join("hallowee", command[0]); //this gives an error
char *join(const char* s1, const char* s2)
{
char* result = malloc(strlen(s1) + strlen(s2) + 1);
if (result)
{
strcpy(result, s1);
strcat(result, s2);
}
return result;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您编写的函数需要两个 C 字符串(即两个
const char *
变量)。在这里,您的第二个参数是command[0]
,它不是一个指针 (const char *
),而是一个简单的“n”字符 (const char
) >)。然而,该函数认为您传递的值是一个指针,并尝试在由字母“n”的 ASCII 值给出的内存地址中查找字符串,这会导致麻烦。编辑:要使其工作,您必须更改
join
函数:The function you wrote requires two C-strings (i.e. two
const char *
variables). Here, your second argument iscommand[0]
which is not a pointer (const char *
) but a simple 'n' character (const char
). The function, however, believes that the value you passed is a pointer and tries to look for the string in memory adress given by the ASCII value of the letter 'n', which causes the trouble.EDIT: To make it work, you would have to change the
join
function:如果您希望加入单个字符,则必须编写一个单独的函数,该函数从
s2
获取要追加的字符数量。If you wish to join a single character, you will have to write a separate function that takes the quantity of characters from
s2
to append.最好的方法是创建一个新函数,允许将单个字符添加到字符串中。
但是,如果您出于某种原因想按原样使用
join()
函数,您也可以按以下步骤操作:The best is to create a new function that allows adding a single char to a string.
But if you would like to use the
join()
function as it is for some reason, you can also proceed as follows: