【发布时间】:2019-10-19 17:22:46
【问题描述】:
谁能解释一下为什么这段代码...
// main.c
#include <stddef.h>
static const int g_a = 1;
static const char* g_b = "hello";
static const char* g_c[] = { "a", "b", NULL };
typedef struct Foo
{
int a;
const char* b;
const char** c;
} Foo;
static Foo f[] =
{
{ g_a,
g_b,
g_c }
};
int main( int argc, char* argv[] )
{
return 0;
}
...产生此错误:
> gcc --version && gcc -g main.c
gcc (GCC) 8.2.1 20181215 (Red Hat 8.2.1-6)
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
main.c:19:5: error: initializer element is not constant
g_b,
^~~
main.c:19:5: note: (near initialization for 'f[0].b')
我了解到编译器要求一个常量来初始化f[0].b,所以下面的初始化是编译错误的解决方法:
static Foo f[] = { { g_a, "hello", g_c } };
但是为什么编译器在 f[0].c 的初始化时没有发出类似的“需要常量”错误?(或者,就此而言,f[0].a?)这是为什么只有f[0].b 的问题?
【问题讨论】:
-
那将在 C++ 中编译。然而,在 C 中,您需要将这些编译时常量替换为预处理器时常量(即,使用
#define)。 -
@goodvibration - 谢谢,明白了,但我特别好奇为什么这只适用于
char*而不适用于char** -
如果你让 g_c 成为一个指针而不是一个数组(并将它指向一个有效的地方),它作为一个 const 初始化器也会变得无效。
标签: c compiler-errors initialization