我有2個定義,其中一個帶有一個字符串,另一個帶有一個數字。如何從字符串和數字定義一個常量數組。這個數組中還有一些額外的常量。C字符串到陣列
我該如何編寫這段代碼,使之在數組foobar中具有0x22,0x41,0x42,0x42,0x21,來自定義的FOO和BAR?
#define FOO "AB"
#define BAR 33
extern int rs232_write(const unsigned char *data, unsigned char count);
const unsigned char foobar[] =
{
0x22,
FOO[0], /*what must i put here, this do not work*/
FOO[1],
0x42,
BAR,
};
int main(void)
{
rs232_write(foobar,sizeof(foobar));
return 1;
}
在GCC,例如,我得到的錯誤:
./001.c:9:5: error: initializer element is not constant
FOO[0], /*what must i put here*/
^
絃樂總是具有相同的長度。 我也試着在其他的方式:我也得到一個錯誤
#define FOO "AB"
#define BAR 33
extern int rs232_write(const unsigned char *data, unsigned char count);
const char foobar[] = \
"\x22" \
FOO \
"\x42" \
BAR /*what must i put here, this also not work*/
int main(void)
{
rs232_write(foobar,sizeof(foobar));
return 1;
}
這裏,例如GCC打印:
./002.c:2:13: error: expected ‘,’ or ‘;’ before numeric constant
#define BAR 33
^
我就沒有太大的空間,微控制器的工作,所以我會喜歡避免在運行時創建數組,我的編譯器只支持C89。
有什麼不對你告訴我們的代碼? –
查看評論,編譯器不接受它(也試用gcc),「錯誤:初始化器元素不是常量」和「錯誤:預計','或';'數字常量之前」 – 12431234123412341234123
當發佈關於構建錯誤的問題時,在問題的正文中始終包含確切的錯誤(未編輯和未修改,最重要的*完整*表格)。最好是完整版本日誌的直接複製粘貼。 –