C &引用;无效初始值设定项“;错误

C &引用;无效初始值设定项“;错误,c,C,为什么不编译?我得到: [错误]无效的初始值设定项 #包括 int main() { int i=2; 字符s[100]=(i==2)?“botton”:“瓶子”; printf(“%c”,s[0]); 返回0; } 使用-Wall编译显示错误: $ gcc -Wall test.c test.c:5:10: error: array initializer must be an initializer list or string literal char s[100] = (i ==

为什么不编译?我得到:

[错误]无效的初始值设定项

#包括
int main()
{
int i=2;
字符s[100]=(i==2)?“botton”:“瓶子”;
printf(“%c”,s[0]);
返回0;
}

使用
-Wall
编译显示错误:

$ gcc -Wall test.c
test.c:5:10: error: array initializer must be an initializer list or string literal
    char s[100] = (i == 2)? "botton":"bottle";
         ^
1 error generated.
但是,您可以使用strcpy()进行初始化。:


但是,不能将
静态字符*s
与此初始值设定项一起使用,因为它在编译时不是常量。

数组的初始值设定项必须是常量初始值设定项列表
s
是一个
char
-数组字符串文字或常量数组初始值设定项

gcc有一个扩展,允许使用非常量表达式初始化自动变量,因此它可能适用于gcc。其他编译器(如clang)也可能(!)允许这样做。无论哪种方式,都需要启用扩展

这适用于所有ISO-C版本(链接适用于C11)


但是,您可以使用
char*s
const char*
,如果您只使用字符串文本)。这允许使用正常表达式,包括非常量。

寻求调试帮助的问题(“为什么此代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建一个最小、完整且可验证的示例。根据第6.7.9节,可以使用字符串文字或括号内的初始值设定项列表初始化
char
数组。条件表达式不是这些东西中的任何一个。是的,这是正确的,但不应该
chars[]=((i==2)?“botton”:“瓶子”)工作,但我选中了,
char*s=((i==2)?“botton”:“瓶子”)正在工作。数组不是指针,尽管它们在某些方面的行为可能类似。@不,它的计算结果是
const char*
。任何东西都不能算作文字;文本是值的文本-文本-表示。类似地,
(i==2)?34 : 56;
的计算结果不是整数文本,而是
int
(其值为34或56)。@molbdnilo:不,它的计算结果是
const char*
如果这样做的话
char s[]=((2==2)?“botton”:“瓶子”)??@haris:我想是的(现在无法测试)。C11似乎允许对
auto
使用变量初始值设定项。数组的初始值设定项不能是任意表达式(常量或非常量)。它必须是初始值设定项列表或字符串文字(对于字符数组)。C11不会更改此设置。@interjay:已编辑。只是花了一些时间在标准中查找。请删除DV。
$ gcc -Wall test.c
test.c:5:10: error: array initializer must be an initializer list or string literal
    char s[100] = (i == 2)? "botton":"bottle";
         ^
1 error generated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    int i = 2;
    char s[100] = {0};
    strcpy(s, (i == 2) ? "botton" : "bottle");
    printf("%c\n", s[0]);
    return EXIT_SUCCESS;
}
char *s = (i == 2) ? "botton" : "bottle";