将char*复制到另一个char []

Pil*_*Dev -1 c++ arrays string char

我有一个关于string/char的简单问题.我试图实现这样的基本系统;

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

int main()
{
    //I'll use 'char*' for socket receive buffer!
    const char* input = "This is a test!";
    char n[4];
    strncpy(n, input, 4);
    printf("%s\n%i\n", n, strlen(n));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到了这个输出:

Thisd0@
7
Run Code Online (Sandbox Code Playgroud)

怎么了?这是一个简单的for/while循环(IDK).

Dan*_*ite 7

You still need to put a null-terminating char (\0) at the end.

char n[5] = { '\0' }; // Initializes the array to all \0
strncpy(n, input, 4);
Run Code Online (Sandbox Code Playgroud)