在VS2008中使用char []的问题 - 为什么strcat追加到空数组的末尾?

tgh*_*tgh 1 c++ arrays char

我传递一个空的char数组,我需要递归填充使用strcat().但是,在VS调试器中,数组不是空的,它充满了一些我不认识的奇怪的垃圾字符.然后strcat()追加到这些垃圾字符的末尾而不是数组的前面.

我也试过了 encoded[0] = '\0'在传递数组之前清除垃圾,但是strcat()不会在递归调用上附加任何内容.

这是提供数组并调用递归函数的代码:

char encoded[512];
text_to_binary("Some text", encoded);
Run Code Online (Sandbox Code Playgroud)

这是递归函数:

void text_to_binary(const char* str, char* encoded)
{   
    char bintemp[9];
    bintemp[0] = '\0';

    while(*str != '\0')
    {
        ascii_to_binary(*str, bintemp);
        strcat(encoded, bintemp);
        str++;
        text_to_binary(str, encoded);
    }
}
Run Code Online (Sandbox Code Playgroud)

到底是怎么回事?

PS.我不能用std::string- 我坚持了char*.

编辑:这是阵列中的垃圾字符:ÌÌ""......

小智 6

您没有初始化阵列.更改:

char encoded[512];
Run Code Online (Sandbox Code Playgroud)

char encoded[512] = "";
Run Code Online (Sandbox Code Playgroud)