C++ 字符数组的初始化字符串太长错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21407898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
initializer-string for array of chars is too long error
提问by Praveen Gowda I V
I am working on a BlackHyman Game using C++, and I have the following piece of code within it where I am getting an error
我正在使用 C++ 开发 BlackHyman 游戏,其中包含以下代码,但出现错误
typedef struct
{
int value;
char suit[8];
char name[8];
}Deck;
Deck Cards[52] = {{ 1,"Ace","Hearts"},{ 2, "Two","Hearts"}, { 3, "Three", "Hearts"}, { 4, "Four","Hearts"}, { 5,"Five","Hearts"},{ 6,"Six", "Hearts06"},
{ 7,"Seven","Hearts"},{ 8,"Eight","Hearts"},{ 9,"Nine","Hearts"},{ 10,"Ten","Hearts"},{10,"Hyman","Hearts"},{10,"Queen","Hearts"},{10,"King","Hearts"},
{ 1,"Ace","Clubs"},{2, "Two", "Clubs"},{3,"Three","Clubs"},{4,"Four","Clubs"},{5,"Five","Clubs"},{6,"Six","Clubs"},{7,"Seven","Clubs"},{8,"Eight","Clubs"},
{ 9,"Nine","Clubs"},{10,"Ten","Clubs"},{10,"Hyman","Clubs"},{10,"Queen","Clubs"},{10,"King","Clubs"},
{ 1,"Ace","Diamonds"},{2,"Two","Diamonds"},{3,"Three","Diamonds"},{4,"Four","Diamonds"},{5,"Five","Diamonds"},{6,"Six","Diamonds"},{7,"Seven","Diamonds"},
{ 8,"Eight","Diamonds"},{9,"Nine","Diamonds"},{10,"Ten","Diamonds"},{10,"Hyman","Diamonds"},{10,"Queen","Diamonds"},{10,"King","Diamonds"},
{ 1,"Ace","Spades"},{ 2,"Two","Spades"},{3,"Three","Spades"},{4,"Four","Spades"},{5,"Five","Spades"},{6,"Six","Spades"},{7,"Seven","Spades"},
{ 8,"Eight","Spades"},{ 9,"Nine","Spades"},{10,"Ten","Spades"},{10,"Hyman","Spades"},{10,"Queen","Spades"},{10,"King","Spades"}};
The erroris
该错误是
Main.c:39:127: error: initializer-string for array of chars is too long [-fpermissive]
Line 39is the last line in the code posted above
第 39行是上面发布的代码中的最后一行
Please help me in figuring out why the compiler is throwing an error
请帮我弄清楚为什么编译器会抛出错误
回答by Joseph Mansfield
The string "Diamonds"
has 9 characters including the null terminating character. Therefore, name
must have at least 9 elements.
该字符串"Diamonds"
有 9 个字符,包括空终止字符。因此,name
必须至少有 9 个元素。
However, it looks like your name
member should be called suit
and vice versa.
但是,看起来您的name
成员应该被调用suit
,反之亦然。
回答by Ajay
Instead of:
代替:
int nMyArray[8]= {5,6,5,4,6,7,4,2};
Prefer this:
更喜欢这个:
int nMyArray[]= {5,6,5,4,6,7,4,2};
When you are initializing an array. The former one requires you to specify size. The latter one computes the size (at compile time only).
初始化数组时。前一个要求您指定大小。后者计算大小(仅在编译时)。