Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is __flexarr and how/why do c programmers use it?

Tags:

c

In sys/inotify.h (inotify.h), following struct is defined:

struct inotify_event
{
  int wd;               /* Watch descriptor.  */
  uint32_t mask;        /* Watch mask.  */
  uint32_t cookie;      /* Cookie to synchronize two events.  */
  uint32_t len;         /* Length (including NULs) of name.  */
  char name __flexarr;  /* Name.  */
};

I can't find any definitions for __flexarr in the code. Where would I search for it?

In an unrelated project I found #define __flexarr [1] which I assume does something similar, but this definition does not make much sense to me (being quite unfamiliar with C).

The only thing I know is that you can store strings of various length in it, but I completely lack the understanding of how/why this works.

Does anybody care to explain? Thanks.

like image 776
somesoaccount Avatar asked Feb 05 '14 21:02

somesoaccount


1 Answers

It's the struct hack. C99 added it officially in the form of "flexible array member".

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.

The sys/cdefs.h I have says:

#if __GNUC_PREREQ (2,97)
/* GCC 2.97 supports C99 flexible array members.  */
# define __flexarr      []
#else
# ifdef __GNUC__
#  define __flexarr     [0]
# else
....

If you are writing new code, the standard-mandated way to use it is with just a [].

like image 134
cnicutar Avatar answered Oct 12 '22 19:10

cnicutar