c - 在结构中使用指针和零元素数组的区别

标签 c struct coding-style

这两种实现有何不同:

struct queue {
    int a;
    int b;
    q_info *array;
};

struct queue {
    int a;
    int b;
    q_info array[0];
};

最佳答案

第二个 struct 不使用零元素数组 - 这是 C99 之前的技巧,用于制作灵活的数组成员。不同之处在于,在第一个片段中,您需要两个 malloc - 一个用于 struct,一个用于 array,而在第二个片段中您可以在一个 malloc 中完成这两个操作:

size_t num_entries = 100;
struct queue *myQueue = malloc(sizeof(struct queue)+sizeof(q_info)*num_entries);

代替

size_t num_entries = 100;
struct queue *myQueue = malloc(sizeof(struct queue));
myQueue->array = malloc(sizeof(q_info)*num_entries);

这让您可以节省释放次数,提供更好的引用局部性,还可以节省一个指针的空间。

从 C99 开始,您可以从数组成员的声明中删除零:

struct queue {
    int a;
    int b;
    q_info array[];
};

关于c - 在结构中使用指针和零元素数组的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19293571/

相关文章:

c - 使过程像二叉树一样,让每个 child 做不同的事情

c - 使用 .h 文件中声明的 C 类型

ios - 将 swift 4 字符串转换为 c unsigned char *

c - 在 Eclipse 中将 mpifort 设置为编译器

css - 样式化可放置在页面中任何位置的元素的最佳实践

coding-style - 您为成员变量使用哪种前缀?

json - 如何在swift中处理不同的JSON HTTP响应

c++ - 使用 std::array 与数组传递对象数组

c++ - 在 union 中获取 sizeof 匿名结构

ios - 带有加载事件指示器的 UITableView 子类