Char数组打印比我想要的更多

Dan*_*.Lu 1 c arrays printf char

为什么它会在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);

}
Run Code Online (Sandbox Code Playgroud)

产量

command =COMMANDsCOMMAND /desktop/document/myfilename 

Process finished with exit code 0
Run Code Online (Sandbox Code Playgroud)

Mur*_*nik 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';
Run Code Online (Sandbox Code Playgroud)

  • 我怀疑这个问题可能有两个重复:(( (2认同)