2014-04-14 254 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,};' –