警告:初始化元素不是常量

gla*_*man 2 c

所有,

在编译时,我有以下C代码,

static struct 
{
    const char* val;
    const char* parse_key;
    int len;  //parse key length
    void (*parse_routine) (const char* after, rtsp_sdp_t* response);
} sdp_header[] =
{
#define SDP_FILL_STRUCT(a,b) {#a, b, strlen(b), sdp_##a}
    SDP_FILL_STRUCT(attr_control, "a=control:"),    
    SDP_FILL_STRUCT(attr_framerate,"a=framerate:"),
    SDP_FILL_STRUCT(attr_range, "a=range:"),    
    {'\0', '\0', 0, (void*)0},  

};
Run Code Online (Sandbox Code Playgroud)

为什么它会发出以下错误:

:330: warning: initializer element is not constant
:330: warning: (near initialization for 'sdp_header[0]')
:331: warning: initializer element is not constant
:331: warning: (near initialization for 'sdp_header[1]')
:332: warning: initializer element is not constant
:332: warning: (near initialization for 'sdp_header[2]')
:333: warning: initializer element is not constant
Run Code Online (Sandbox Code Playgroud)

我不知道究竟是什么原因,请你给我一些帮助.谢谢

AnT*_*AnT 5

在C89/90中,所有支撑封闭的初始化器都需要是常数.在C99和更高版本中,具有静态存储持续时间的对象的大括号括起初始化器必须是常量.

这就是你的情况:sdp_header是一个具有静态存储持续时间的数组,这意味着你只允许在它之间使用常量{}.

看起来你的所有初始化器都是常量strlen.函数调用不会产生常量.在您的具体情况下,您可以替换strlensizeof

#define SDP_FILL_STRUCT(a,b) {#a, b, sizeof b - 1, sdp_##a}
Run Code Online (Sandbox Code Playgroud)

但它只有在b代表文字字符串时才会起作用(在你的例子中就是这种情况).

此外,根据您的意图,您的上一个初始化程序是错误的还是误导性的.最后一个元素的值valparse_key应该是什么?如果你想要空字符串,那么它应该是

{ "", "", 0, NULL }
Run Code Online (Sandbox Code Playgroud)

如果你想要空指针,那么它应该是

{ NULL, NULL, 0, NULL }
Run Code Online (Sandbox Code Playgroud)

要么

{ 0, 0, 0, 0 }
Run Code Online (Sandbox Code Playgroud)

甚至仅仅是一个人

{ 0 }
Run Code Online (Sandbox Code Playgroud)

您的当前'\0'将作为空指针常量工作,但指定空指针常量是一种误导和奇怪的方式.

你为什么0void *为函数指针成员做套管也不清楚.为什么?只写NULL或简单0.没有必要的演员.如果你想要一个演员,至少把它投到合适的类型.void *来自哪里?