如何在没有空终止符的情况下初始化char数组?

编程入门 行业动态 更新时间:2024-10-27 03:41:29
本文介绍了如何在没有空终止符的情况下初始化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数组?

本文发布于:2023-07-30 11:06:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1248841.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   初始化   情况下   如何在   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!