Char数组的打印量比我在C语言中想要的要多

时间:2018-09-15 16:20:12

标签: c arrays char printf

为什么要在char数组命令末尾打印额外的“ COMMAND / desktop / document / myfilename”?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char c_header[] = "COMMAND /desktop/document/myfilename \r\n\r\n";

    char command[8];

    for (size_t i = 0; i < 8 ; i++){
        command[i] = c_header[i];
    }
    command[7] = 's';

    printf( "command =%s\n", command);

}

输出

command =COMMANDsCOMMAND /desktop/document/myfilename 

Process finished with exit code 0

2 个答案:

答案 0 :(得分:5)

中的字符串以\0终止。如果您尝试将不以\0结尾的字符数组当作字符串(例如,printf对其进行字符串处理),它将被溢出直到您按下下一个\0碰巧在你的堆里。

长话短说,您需要明确确保在字符串的末尾有一个\0

/* Added an extra char for the '\0' */
char command[9]; 

for (size_t i = 0; i < 8 ; i++){
    command[i] = c_header[i];
}
command[7] = 's';
command[8] = '\0';

答案 1 :(得分:1)

您需要以<'\0'> or NULL或整数0结束字符串。