2019/06/10 更新
1. 「C99 6.7.2.1 Structure and union specifiers」提到 flexible array member 只允許在 structure 的最後一個元素,故 UEFI 的 EFI_LOAD_OPTION 應該是用了某種方式達到一個以上的未定義長度的 array,故並不是 standard 裡的 flexible array member。
2. 原文如下:「As a special case, the last element of a structure with more than one named member may
have an incomplete array type; this is called a flexible array member.」
#include <stdio.h>
#include <stdlib.h>
typedef struct Item {
int length;
// flexible array member
int data[];
} Item;
int main(void)
{
// this is decided dynamically.
int realCount = 4;
int realSize = realCount * sizeof(int);
Item *p = (Item*)malloc(sizeof(Item) + realSize);
p->length = realSize;
// give values
for (int i = 0; i < realCount; i++) {
p->data[i] = i;
}
// check size
printf("sizeof(Item) is %d \n", sizeof(Item));
// check values
for (int i = 0; i < realCount; i++) {
printf("p->data[%d] = %d \n", i, p->data[i]);
}
free(p);
system("pause");
return 0;
}
執行結果
sizeof(Item) is 4
p->data[0] = 0
p->data[1] = 1
p->data[2] = 2
p->data[3] = 3
沒有留言:
張貼留言