7 Eylül 2018 Cuma

Flexible Array Member

Giriş
struct'ın son elemanının array olmasıdır
struct s {
     int a;
 };      

 struct z {
     int a;
     struct s b[];
 };
Açıklaması şöyle. Böylece struct'ı malloc yaparken array için de bellek alanı hesaplaması yapmaya gerek kalmaz.
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. In most situations, the flexible array member is ignored. In particular, the size of the structure is as if the flexible array member were omitted except that it may have more trailing padding than the omission would imply.
Örnek
Elimizde şöyle bir kod olsun
struct Foo {
  ...

  int         len;
  LetterData  letters[];
};
Daha sonra bu yapı için bellek ayrılır. Şöyle yaparız.
Foo *pFoo = malloc(sizeof(Foo)+sizeof(LetterData)*len);   
C99'dan Önce
array'in büyüklüğü 0 ile belirtiliyordu. Bu bir GCC extension. Açıklaması şöyle.
The C standard committee recognized that this gcc feature was useful, so they added flexible array members to the C language in 1999. Since then, the gcc feature is to be regarded as obsolete, as using the C standard flexible array member is to prefer.
Örnek
Şöyle yaparız.
struct Foo {
  size_t size;
  int data[0];
};
Yine aynı şekilde şöyle yaparız.
Foo* pFoo = malloc(sizeof(Foo) + size * sizeof(int));
C++
Açıklaması şöyle. Yani kullanılmamalı.
Using open sized array as the last member of struct is quite common practice in C. And it was standardized in C99 (2.6.7."flexible array member").

C++ standard says nothing about "flexible array members". So it is not guarantee that it works in C++. But the most of the popular compilers support this feature even for C++:

gcc
msvc
clang "Note that clang does support flexible array members (arrays with a zero or unspecified size at the end of a structure)"

So actually it is possible to use it, but this is very dangerous practice. You should try to avoid it, and you need to be very careful if you decide to use it.





Hiç yorum yok:

Yorum Gönder