C 字符到字符串(将字符传递给 strcat())

标签 c string char strcat

我的问题是将字符转换为字符串 我必须向 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/

相关文章:

使用递归函数检查字符在字符串中出现的次数

C中的字符数组比较

regex - 使用 Python 查找头韵单词序列

C++ 换行不翻译

C++ String.h Char Tables 没有 strstr 的截断词

c++ - 如何在 C 和 C++ 中设计具有并行接口(interface)的库

c - 代码中的 "Floating point exception"不包含 float

c - 使用数组和指针

c - 如何检查字符串是否在文件中

c - va_arg 字符串段错误