为什么要在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
答案 0 :(得分:5)
c中的字符串以\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
结束字符串。