2017-11-11 46 views
-1

我已經一個結構由下式定義:Ç - 寫入結構的數組 - 不可修改的左值

typedef struct 
{ 
    char name[CANDY_NAME_LEN]; 
    bool vegan; 
} candy; 

我定義這些結構的尺寸爲10的數組:

const candy candy_db[NUM_OF_CANDIES]; 

,並嘗試以填補該陣列:

strcpy_s(candy_db[0].name, sizeof(candy_db[0].name), "Apple"); 
candy_db[0].vegan = true; 

但設置爲真數組中的第一個元素(或任何元素)的布爾字段給我一個錯誤: 表達式必須是可修改的左值。

是什麼問題?

感謝

+1

你給const,這沒關係。當'strcpy_s'不給出警告時錯誤 –

+1

const表示只讀,不可變。 – LethalProgrammer

回答

1

const candy candy_db[NUM_OF_CANDIES];

你已經爲你的陣列const,所以沒有它的元素可以修改。

+0

但練習說明說定義一個「糖果」的恆定數組,所以我該怎麼做? – Nben

+0

你可以通過初始化數組來初始化數組,而不是'strcpy',而是初始化: 'const candy candy_db [NUM_OF_CANDIES] = {{「Apply」,true}};' – immortal

+0

所以當定義一個const時,唯一的填充它的方式是什麼時候初始化? 以後如何修改?我嘗試過使用指針,但是我的語法與struct – Nben