将每const char*
个括号括起来,可以解决以下问题:
static const char* const stateNames[5] =
{
("Init state"),
("Run state"),
("Pause state") //comma missing
("Pause state3"),
("Error state")
};
如果忘记了逗号,将出现类似于:error: called object is not a function or function pointer
的编译错误
LIVE DEMO个
请注意,如果您忘记了逗号,实际发生的情况是,C将实际连接两个(或更多)字符串,直到下一个逗号或数组结束.例如,假设您忘记了逗号,如下所示:
static const char* const stateNames[] =
{
"Init state",
"Run state",
"Pause state" //comma missing
"Pause state3" //comma missing
"Error state"
};
int main(void)
{
printf("%s\n", stateNames[0]);
return 0;
}
这就是gcc-9.2
generates(其他编译器生成类似代码):
.LC0:
.string "Init state"
.string "Run state"
.string "Pause statePause state3Error state" ; oooops look what happened
.quad .LC0
.quad .LC1
.quad .LC2
main:
push rbp
mov rbp, rsp
mov eax, OFFSET FLAT:.LC0
mov rdi, rax
call puts
mov eax, 0
pop rbp
ret
很明显,最后三个字符串是连接在一起的,并且数组的长度不是您预期的长度.