![](/img/trans.png)
[英]Why the size differs? sizeof(a) vs sizeof(&a) of an array?
[英]sizeof(array) within array declaration of implicit size
考慮以下常見的數組定義,注意數組本身必須包括總大小:
#define BUFSZ 3
uint8_t buffer[BUFSZ] = {
BUFSZ, 0xFF, 0x00
}
當您大量更改緩沖區並且它變得足夠大以至於跟蹤每個更改比每次從頭開始計數更容易時,這不是很方便。 當然,這樣的事情是可能的:
#define BUFSZ 3
uint8_t buffer[BUFSZ] = {
sizeof(buffer), 0xFF, 0x00
}
或者相反
#define BUFSZ 3
uint8_t buffer[] = {
BUFSZ, 0xFF, 0x00
}
但是兩者的組合根本不需要計數是不可能的:
uint8_t buffer[] = {
sizeof(buffer), 0xFF, 0x00
}
這導致invalid application of 'sizeof' to incomplete type 'uint8_t[]' {aka 'unsigned char[]'}
注意我使用的是 arm-none-eabi-gcc 編譯器,但這也適用於 gcc。
對於需要在編譯時定義需要存儲其大小的數組的情況,最佳實踐是什么?
我想一個選項可能是保留那個位置並在運行時設置它,在我的情況下可以工作,但也可以防止它保存在只讀內存中。
#define INIT 0xFF, 0x00
#define SOF(x) (sizeof((char []){x})+1)
char buffer[] =
{
SOF(INIT) , INIT
};
要么
#define SOF(name, ...) char name[] = {(sizeof((char []){__VA_ARGS__})+1), __VA_ARGS__}
SOF(buffer,255,0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.