抑制“输出在终止 nul 之前被截断”

And*_*eKR 2 c gcc

我正在构建一个必须包含特定字符串字符序列的二进制结构。要设置字符序列,我使用

struct {
    char preamble[6];
    uint8_t check;
} msg;

strncpy(msg.preamble, "abcdef", 6);
Run Code Online (Sandbox Code Playgroud)

这给了我一个警告:

src\main.cpp:41:9: warning: 'char* strncpy(char*, const char*, size_t)' output truncated before terminating nul copying
6 bytes from a string of the same length [-Wstringop-truncation]
Run Code Online (Sandbox Code Playgroud)

我希望构建日志中不包含警告,以便我可以更快地看到实际问题。

我怎样才能修复/抑制这个警告?

dbu*_*ush 6

如果您拥有的不是字符串,请不要将其视为字符串,即不要使用strncpy. memcpy代替使用。

memcpy(msg.preamble, "abcdef", 6);
Run Code Online (Sandbox Code Playgroud)