在C不好的做法使用灵活的阵列成员? [英] Is using flexible array members in C bad practice?

查看:159
本文介绍了在C不好的做法使用灵活的阵列成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我读,在C采用灵活的数组成员是穷人的软件工程实践。然而,这种说法没有得到任何参数的支持。这是一个公认的事实?

(灵活阵列成员是在C99引入了一个C特征,其中可以声明的最后一个元素是未指定大小的数组,例如:)

 结构头{
    为size_t LEN;
    unsigned char型数据[];
};


解决方案

我之所以会给不这样做的是,它不值得以配合您的code,以C99只是为了使用此功能。

问题的关键是,你可以随时使用下面的语句:

 结构头{
  为size_t LEN;
  unsigned char型数据[1];
};

这是完全可移植的。然后你就可以在阵列中分配为n个元素的内存时取1到数据

  PTR =的malloc(sizeof的(结构头)+(N-1));

如果你已经有了C99的要求,建立你的code任何其他原因,或者你是针对一个特定的编译器,我看不出有什么坏处。

I recently read that using flexible array members in C was poor software engineering practice. However, that statement was not backed by any argument. Is this an accepted fact?

(Flexible array members are a C feature introduced in C99 whereby one can declare the last element to be an array of unspecified size. For example: )

struct header {
    size_t len;
    unsigned char data[];
};

解决方案

The reason I would give for not doing it is that it's not worth it to tie your code to C99 just to use this feature.

The point is that you can always use the following idiom:

struct header {
  size_t len;
  unsigned char data[1];
};

That is fully portable. Then you can take the 1 into account when allocating the memory for n elements in the array data :

ptr = malloc(sizeof(struct header) + (n-1));

If you already have C99 as requirement to build your code for any other reason or you are target a specific compiler, I see no harm.

这篇关于在C不好的做法使用灵活的阵列成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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