初始化固定大小的 char 数组时没有编译器错误,没有足够的空间容纳空终止符 [英] No compiler error when fixed size char array is initialized without enough room for null terminator

查看:13
本文介绍了初始化固定大小的 char 数组时没有编译器错误,没有足够的空间容纳空终止符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下 c char 数组:

Suppose I have the following c char arrays:

char okaysize4[5] = "four";   // line 5
char toosmall4[4] = "four";   // line 6
char toosmall3[3] = "four";   // line 7

当我使用 gcc 4.4.7 编译时,出现以下错误:

When I compile with gcc 4.4.7, I get the following error:

array.c:7: 警告:字符数组的初始化字符串太长

array.c:7: warning: initializer-string for array of chars is too long

第 7 行会出现此错误,因为我试图将 5 个字符 ("four" + ) 填充到 3 元素数组中.由于 5 元素数组足够大,所以第 5 行也不会出现错误.

This error is expected for line 7, as I am trying to stuff 5 chars ("four" + ) into a 3 element array. Also no error is expected for line 5 as the 5 element array is big enough.

但令我惊讶的是,第 6 行没有类似的错误.在 toosmall4 中最终被初始化的是一个未终止的字符串,这可能会导致各种麻烦.

However I'm surprised there is no similar error for line 6. What ends up getting initialized in toosmall4 is an unterminated string, which can cause all sorts of trouble.

我的理解是 c 字符串文字 "four" 应该是五个字符长,由于空终止符.实际上 sizeof("four") 是 5.那为什么编译器在这里没有报错呢?

My understanding is that the c string literal "four" should be five characters long, due to the null terminator. In fact sizeof("four") is 5. So why does the compiler not give an error here?

有什么方法可以改变我的声明/定义/初始化,以便在这种情况下标记错误?

Is there some way I can alter my declaration/definition/initialization so that an error is flagged in this case?

推荐答案

这是第 6 行的预期行为,来自 草案 C99 标准 部分 6.7.8 初始化14 说(强调我的):

This is expected behavior for line 6, from the draft C99 standard section 6.7.8 Initialization paragraph 14 says (emphasis mine):

字符类型的数组可以由字符串初始化字面量,可选地用大括号括起来.的连续字符字符串文字(包括终止空字符如果有空间或数组大小未知)初始化数组的元素.

An array of character type may be initialized by a character string literal, optionally enclosed in braces. Successive characters of the character 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.

在 C11 草案标准中,类似措辞的相关部分是 6.7.9 段落 14,并作为 C 常见问题解答说:

In the C11 draft standard the relevant section with similar wording is 6.7.9 paragraph 14, and as the C FAQ says:

因此该数组不是真正的 C 字符串,不能与strcpy、printf的%s格式等

The array is therefore not a true C string and cannot be used with strcpy, printf's %s format, etc.

正如 Keith Thompson 所说,C++ 更为严格,C++ 标准草案中的相关部分如下所述:

As Keith Thompson noted, C++ is stricter, the relevant section in the draft C++ standard says the following:

初始化器的个数不得多于数组元素的个数.[ 例子:

There shall not be more initializers than there are array elements. [ Example:

char cv[4] = "asdf"; // error

格式不正确,因为隐含的尾随 '' 没有空格.——结束示例]

is ill-formed since there is no space for the implied trailing ’’. —end example ]

这篇关于初始化固定大小的 char 数组时没有编译器错误,没有足够的空间容纳空终止符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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