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

时间:2018-05-11 18:17:30

标签: c static

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

#include <stdio.h>

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)但我想直接插入它而不进行任何动态分配。问题是什么?为什么我会得到这样的错误!

1 个答案:

答案 0 :(得分:1)

是的,以这种方式使用复合文字是非标准的,它们不被视为&#34;常数&#34;但对象。正确的工具是指定的初始化程序。例如,对于您的类型host_t,初始化程序看起来像

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