Abh*_*ury 4 c struct coding-style
两种实现有何不同:
struct queue {
int a;
int b;
q_info *array;
};
Run Code Online (Sandbox Code Playgroud)
和
struct queue {
int a;
int b;
q_info array[0];
};
Run Code Online (Sandbox Code Playgroud)
das*_*ght 11
第二个struct
不使用零元素数组 - 这是制作灵活数组成员的前C99技巧.不同之处在于,在第一个片段中,您需要两个malloc
s - 一个用于struct
,一个用于array
,而在第二个片段中,您可以同时执行以下两个操作malloc
:
size_t num_entries = 100;
struct queue *myQueue = malloc(sizeof(struct queue)+sizeof(q_info)*num_entries);
Run Code Online (Sandbox Code Playgroud)
代替
size_t num_entries = 100;
struct queue *myQueue = malloc(sizeof(struct queue));
myQueue->array = malloc(sizeof(q_info)*num_entries);
Run Code Online (Sandbox Code Playgroud)
这使您可以节省解除分配的数量,提供更好的引用位置,还可以节省一个指针的空间.
从C99开始,您可以从数组成员的声明中删除零:
struct queue {
int a;
int b;
q_info array[];
};
Run Code Online (Sandbox Code Playgroud)