C静态初始化元素不是常量错误

这是我在C语言中的源代码我想用静态,外侧函数定义基本数据

#include  typedef struct { char * URI; char * file; } redirect_t; typedef struct { char * URI; char * file; long long content_length; } content_t; typedef struct { content_t contents[10]; redirect_t redirects[10]; } host_t; typedef struct { unsigned max_requests; host_t hosts[10]; } addr_t; static addr_t addr_list[] = { (addr_t) { 24, { (host_t) { { (content_t) { "URI" }, (content_t) { "URI2" }, (content_t) { "URI3" }, }, { (redirect_t) { "URI5" }, (redirect_t) { "URI6" }, (redirect_t) { "URI7" }, } } } } }; int main() { return 0; } 

但我得到(初始化元素不是常数)错误

这是我的编译结果

 C:\Users\x\Documents\C Projects\untitled\main.c:27:26: error: initializer element is not constant (host_t) { ^ C:\Users\x\Documents\C Projects\untitled\main.c:27:26: note: (near initialization for '(anonymous).hosts') C:\Users\x\Documents\C Projects\untitled\main.c:25:18: error: initializer element is not constant (addr_t) { 24, ^ C:\Users\x\Documents\C Projects\untitled\main.c:25:18: note: (near initialization for 'addr_list') C:\Users\x\Documents\C Projects\untitled\main.c:25:9: error: initializer element is not constant 

我知道我可以在函数内使用malloc并将数据插入(addr_list)但我想直接插入它而不需要任何动态分配。 问题是什么? 为什么我会得到这样的错误!

是的,以这种方式使用复合文字是非标准的,它们不被视为“常量”而是对象。 正确的工具是指定的初始化器。 例如,对于你的类型host_t ,初始化器看起来像

  { .contents = { .URI = "URI", }, .redirects = { .URI = "URI5", }, },