我的问题是将字符转换为字符串 我必须向 strcat() 传递一个 char 以附加到字符串,我该怎么做? 谢谢!
#include <stdio.h>
#include <string.h>
char *asd(char* in, char *out){
while(*in){
strcat(out, *in); // <-- err arg 2 makes pointer from integer without a cast
*in++;
}
return out;
}
int main(){
char st[] = "text";
char ok[200];
asd(st, ok);
printf("%s", ok);
return 0;
}
最佳答案
因为 ok
指向一个未初始化的字符数组,所以它都是垃圾值,所以连接(通过 strcat
)将从哪里开始是未知的。 strcat
也接受一个 C 字符串(即以 '\0' 字符结尾的字符数组)。给 char a[200] = ""
会给你 a[0] = '\0',然后 a[1] 到 a[199] 设置为 0。
编辑:(添加了代码的更正版本)
#include <stdio.h>
#include <string.h>
char *asd(char* in, char *out)
{
/*
It is incorrect to pass `*in` since it'll give only the character pointed to
by `in`; passing `in` will give the starting address of the array to strcat
*/
strcat(out, in);
return out;
}
int main(){
char st[] = "text";
char ok[200] = "somevalue"; /* 's', 'o', 'm', 'e', 'v', 'a', 'l', 'u', 'e', '\0' */
asd(st, ok);
printf("%s", ok);
return 0;
}
关于C 字符到字符串(将字符传递给 strcat()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2347457/