2014-04-14 252 views
0

我想initalize一个结构,但得到在C以下错误封邮件:初始化结构

错误:初始元素不是常数

错误:(近初始化为“resource01.resource.role” )

对于URL它的工作原理,它只是它不工作中的作用。首先,我有一个角色指针,我分配了变量的地址。我删除了指针,因为我不需要它,我不能为变量赋值。我究竟做错了什么?

static char const resource01Url[] = "/dummy"; 
static int const resource01Role = 2; 
static struct RestResourceNode_S resource01 = 
{ 
    { 
     resource01Url, 
     resource01Role, 
     &DummyHandler_call 
    }, 
    NULL 
}; 

static struct RestResourcesManager_S resourcesManager = 
{ 
    &resource01, &resource01 
}; 

类型RestResourceNode_S定义:

struct RestResourceNode_S 
{ 
    RestResource_T resource; 
    struct RestResourceNode_S const *next; 
} 

和RestResource_t:

struct RestResource_S 
{ 
    char const *url; 

    int const role; 

    retcode_t (*handle)(Msg_T *); 
}; 

typedef struct RestResource_S RestResource_T; 
+0

'resource01Url'不会算作一个常量表达式,数组的位置由连接器确定。 –

回答

0

C99标准§ 6.7.8 ¶ 4说

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

此外,const是不是在C真正的常量在这个意义上,他们没有编译时间常数。这意味着你不能在其中具有静态存储分配的结构的初始化常量对象。但是,如果您的结构具有自动存储分配,则这可以正常工作。

你可以做的是定义const对象作为宏 -

#define resource01Url "/dummy" 
#define resource01Role 2 
0

int const不能算作一个编译时间常数C.你必须将其更改为代替#define

+0

你是什么意思与“将其更改为#定义”? – user3464679

+0

'的#define resource01Role 2' –

+1

对于'int'枚举是比较合适的:'枚举{resource01Role = 2,};' –