如何在没有空终止符的情况下初始化char数组? [英] How to initialize a char array without the null terminator?

查看:141
本文介绍了如何在没有空终止符的情况下初始化char数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char数组是网络消息的一部分,具有明确的长度,因此不需要空终止符。

The char array is a part of network message, which has well defined length, so the null terminator is not needed.

struct Cmd {
    char cmd[4];
    int arg;
}

struct Cmd cmd { "ABCD" , 0 }; // this would be buffer overflow

如何初始化此cmd成员char数组?而不使用 strncpy

How can I initialize this cmd member char array? without using functions like strncpy?

推荐答案

char 数组的大小与初始化程序中的字符数相同。因此 cmd 将没有空终止符。

Terminating null character is ignored if the size of the char array is the same as the number of characters in the initializer. So cmd will not have the null terminator.

C11标准(n1570)中的相关部分是 6.7.9 / 14

The relevant section in the C11 standard (n1570) is 6.7.9/14:


字符类型的数组可以由字符串文字或UTF-8字符串文字初始化,并可选地用大括号括起来。字符串文字的连续字节(包括终止空字符,如果有空间 ,或者数组的大小未知),将初始化数组的元素。

An array of character type may be initialized by a character string literal or UTF−8 string literal, optionally enclosed in braces. Successive bytes of the string literal (including the terminating null character if there is room or if the array is of unknown size) initialize the elements of the array.

语句:

struct Cmd cmd { "ABCD" , 0 };

应为:

struct Cmd cmd  = { "ABCD" , 0 };

这篇关于如何在没有空终止符的情况下初始化char数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆