7
int main(void)
{
    char four[4] = "four";
    return 0;
}

C ++プログラムとしてコンパイルすると、G++はレポートします

xxx.cpp:関数int main():

xxx.cpp:3:エラー:初期化子-文字の配列の文字列が長すぎます

Cプログラムをコンパイルすると、GCCはエラーを報告しません。

予想どおり、割り当ては4バイトすべてを変数に正しくコピーしているように見えます。

だから私の質問は要約すると.....

Cで観察された動作は正しいですか、それともどこかで未定義の動作に触れていますか、それともまったく別のものですか?

4

4 に答える 4

22
于 2010-08-19T16:44:03.163 に答える
2

良いでしょう

char four[] = "four";
于 2010-08-19T16:55:30.150 に答える
2

The string "four" actually contains five bytes: the four letters plus a zero byte (\0) as a string terminator. It's been a while since I've written C or C++, but I would guess the C compiler is silently ignoring it for whatever reason.

于 2010-08-19T16:46:12.923 に答える
1

What you're seeing is a difference between C and C++. C allows you to have extra initializers, which are ignored. C++ prohibits this -- if you specify a size for a string (or array) it must be large enough to accommodate all the initializers (including the NUL terminator, in the case of a string), or the code is ill-formed (standardese for "it's not allowed -- expect the compiler to reject it").

于 2010-08-19T17:04:20.847 に答える