使用指针和数组的区别与结构元素为零 [英] Difference between use of pointer and array with zero elements in structs

查看:106
本文介绍了使用指针和数组的区别与结构元素为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在两个不同的实现方式:

 结构队列{
    int类型的;
    INT B:
    q_info *阵列;
};

 结构队列{
    int类型的;
    INT B:
    q_info阵列[0];
};


解决方案

第二个结构不使用零元素的数组 - 这是一个pre- C99把戏使灵活的阵列成员。所不同的是,在第一个片段,你需要两个的malloc 秒 - 一个用于结构,以及一个用于阵列,而在第二个,你可以在一个的malloc 一举两得:

 为size_t NUM_ENTRIES = 100;
结构队列* myQueue中的malloc =(sizeof的(结构队列)+的sizeof(q_info)* NUM_ENTRIES);

而不是

 为size_t NUM_ENTRIES = 100;
结构队列* myQueue中的malloc =(sizeof的(结构队列));
myQueue->阵=的malloc(sizeof的(q_info)* NUM_ENTRIES);

这可以让你节省解除分配的数量,提供参考的地方更好,也节省空间一个指针。

与C99开始,你可以从阵列成员的声明降为零:

 结构队列{
    int类型的;
    INT B:
    q_info数组[];
};

How do the two implementations differ:

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

and

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

解决方案

The second struct does not use an array of zero elements - this is a pre-C99 trick for making flexible array members. The difference is that in the first snippet you need two mallocs - one for the struct, and one for the array, while in the second one you can do both in a single malloc:

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

instead of

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

This lets you save on the number of deallocations, provides better locality of references, and also saves the space for one pointer.

Starting with C99 you can drop zero from the declaration of the array member:

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

这篇关于使用指针和数组的区别与结构元素为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆