[英]How can an array of structs be initialized using a const struct in global scope?
我想使用類似於以下代碼(但要復雜得多-這是一個簡化的示例)來初始化結構數組,但是在編譯過程中出現錯誤“表達式必須具有恆定值”。
typedef struct
{
int x;
int y;
} windowStruct_t;
static const windowStruct_t windowStructInit =
{
.x = 3,
.y = 5,
};
// These get defined differently at times. This is simplified for the example.
#define NUM_ARRAY_ELEMENTS (2)
#define REPEAT_NUM_ARRAY_ELEMENTS_TIMES(x) (x),(x)
// The following line causes the error "expression must have a constant value" twice.
windowStruct_t windowStruct[ NUM_ARRAY_ELEMENTS ] =
{ REPEAT_NUM_ARRAY_ELEMENTS_TIMES( windowStructInit ) };
void someFunction( void )
{
volatile int x = windowStruct[0].x;
}
void anotherFunction( void )
{
volatile int y = windowStruct[1].y;
}
手動擴展宏並用以下代碼替換導致錯誤的行將得到相同的結果:
windowStruct_t windowStruct[ NUM_ARRAY_ELEMENTS ] =
{ windowStructInit, windowStructInit };
但這編譯沒有錯誤:
windowStruct_t windowStruct[ NUM_ARRAY_ELEMENTS ] =
{ { .x = 3, .y = 5 }, { .x = 3, .y = 5 } };
如果我將數組聲明移到函數作用域之內,它的編譯將不會出錯(我忽略了someFunction()和anotherFunction()現在訪問不同數組且它們的生存期不同的事實):
void someFunction( void )
{
windowStruct_t windowStruct[ NUM_ARRAY_ELEMENTS ] =
{ REPEAT_NUM_ARRAY_ELEMENTS_TIMES( windowStructInit ) };
volatile int x = windowStruct[0].x;
}
void anotherFunction( void )
{
windowStruct_t windowStruct[ NUM_ARRAY_ELEMENTS ] =
{ REPEAT_NUM_ARRAY_ELEMENTS_TIMES( windowStructInit ) };
volatile int y = windowStruct[1].y;
}
將數組聲明保留在函數范圍內,如果聲明為“靜態”,則會返回錯誤消息:
void someFunction( void )
{
static windowStruct_t windowStruct[ NUM_ARRAY_ELEMENTS ] =
{ REPEAT_NUM_ARRAY_ELEMENTS_TIMES( windowStructInit ) };
volatile int x = windowStruct[0].x;
}
因此,似乎將數組聲明為自動變量(在堆棧上)時,可以以內存分配為靜態(無論是在函數范圍內還是在全局范圍內,分配為靜態)不允許的方式初始化數組即使沒有“ static”關鍵字)。 有沒有辦法像原始示例一樣使用const結構在全局范圍內初始化數組?
我正在使用C,而不是C ++。 我不想使用動態內存分配。 該編譯器是TI的Code Composer Studio環境中包含的TI ARM編譯器V16.6.0.STS。
const
對象不是C 常量 。 而是使用非自動存儲對象所需的常量 。
定義一個初始化器{ .x = 3, .y = 5 }
typedef struct windowStruct_s {
int x;
int y;
} windowStruct_t;
#define windowStruct_t_default_initializer { .x = 3, .y = 5 }
#define NUM_ARRAY_ELEMENTS (2)
#define REPEAT_NUM_ARRAY_ELEMENTS_TIMES(x) x, x /* no () */
windowStruct_t windowStruct[NUM_ARRAY_ELEMENTS] = {
REPEAT_NUM_ARRAY_ELEMENTS_TIMES(windowStruct_t_default_initializer) };
int someFunction(void) {
volatile int x = windowStruct[0].x;
return x;
}
int anotherFunction(void) {
volatile int y = windowStruct[1].y;
return y;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.