为什么“字符数组的初始化字符串太长"?在 C & 中编译良好不是在 C++ 中?

2021-12-18 00:00:00 gcc string c g++ c++

以下程序在 C 中编译正常,但有警告,但在 C++ 中编译失败.为什么?是什么原因?

Following program compiles fine in C with warnings but fails in compilation in C++. Why? What is the reason?

#include <stdio.h>
int main(void)
{
    char a[5]="Hello";
    a[0]='y';
    puts(a);
    for(int i=0;i<5;i++)
        printf("%c",a[i]);
    return 0;
}

警告:

Warning:[Error] initializer-string for array of chars is too long [-fpermissive] enabled by default

但是如果程序被编译为 C++ 程序,那么 C++ 编译器会出现以下错误:

But if the program is compiled as C++ program then C++ compiler gives following error:

[Error] initializer-string for array of chars is too long [-fpermissive]

我使用的是 GCC 4.8.1 编译器.

I am using GCC 4.8.1 compiler.

推荐答案

简短回答:因为 C 和 C++ 是不同的语言,具有不同的规则.

Short answer: Because C and C++ are different languages with different rules.

长答案:在这两种情况下,原因都是数组对于字符串文字来说太小了.文字由五个可见字符组成,末尾有一个零终止符,因此总大小为 6.

Long answer: In both cases the reason is that the array is too small for the string literal. The literal consists of the five visible characters, with a zero terminator on the end, so the total size is 6.

在 C 中,您可以使用太长的字符串初始化数组;额外的字符会被忽略:

In C, you're allowed to initialise an array with a string that's too long; extra characters are simply ignored:

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

C99 6.7.8/14: 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.

编译器会警告字符串太大,因为它几乎可以肯定表示有错误;但除非您告诉它将警告视为错误,否则它无法拒绝代码.

The compiler helpfully warns that the string is too large, since it almost certainly indicates an error; but it can't reject the code unless you tell it to treat warnings as errors.

在 C++ 中,初始化器不允许大于数组:

In C++, the initialiser isn't allowed to be larger than the array:

C++11 8.5.2/2:初始化器的数量不应多于数组元素.

C++11 8.5.2/2: There shall not be more initializers than there are array elements.

所以,对于那种语言,编译器应该给出一个错误.

so, for that language, the compiler should give an error.

在两种语言中,当您希望字符数组的大小适合字符串字面量初始化程序时,您可以不考虑大小,编译器会做正确的事情.

In both languages, when you want a character array to be the right size for a string literal initialiser, you can leave the size out and the compiler will do the right thing.

char a[] = "hello";  // size deduced to be 6

相关文章