为什么C ++需要6个大小的数组来存储5个字母的单词,而C仅允许5个单词呢? [英] Why does C++ need array of 6 size to store 5 letter word whereas C allows just 5?

查看:173
本文介绍了为什么C ++需要6个大小的数组来存储5个字母的单词,而C仅允许5个单词呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在C和C ++中尝试了以下语句.

I have tried this following statement in C and C++.

char A[5] = {"Hello"};

尽管C接受了这一点,但是C ++抛出错误,指出字符串太长.如果要添加一个空字符,为什么在C中可以接受,但在C ++中不可以?

While C accepts this, C++ is throwing an error saying the string is too long. If there is a null character to be added, why is it accepted in C but not in C++?

推荐答案

请注意, char A [5] = {"Hello"}; 是这两种语言中的错误.必须有空间分配空终止符.

Please note that char A[5]={"Hello"}; is a bug in either language. There must be room to allocate the null terminator.

由于语言6.7.9/14有一个奇怪的特殊规则/语言错误(重点是我的),因此它使用C进行编译:

It compiles in C because the language 6.7.9/14 has an an odd special rule/language bug, emphasis mine:

可以通过字符串文字或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.

这允许使用字符串文字初始化字符数组,该字符串文字的字符数与数组大小完全相同,但是会静默丢弃空终止符.

This allows a character array to be initialized with a string literal which has exactly the same amount of characters as the size of the array, but silently discard the null termination.

C ++修复了此危险的语言错误.

C++ fixed this dangerous language bug.

这篇关于为什么C ++需要6个大小的数组来存储5个字母的单词,而C仅允许5个单词呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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