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

The following structure is defined in sys/inotify.h ( inotify.h ):

 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 not find any definitions for __flexarr in code. Where would I look for him?

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 (completely unfamiliar with C).

The only thing I know is that you can store strings of various lengths in it, but I absolutely lack an understanding of how this works.

Anyone want to explain? Thanks.

+5
source share
1 answer

This is a struct hack . C99 officially added it as a "flexible array element".

As a special case, the last element of the structure with more than one named element may have an incomplete array type; this is called a flexible array element. In most situations, the flexible array element is ignored. In particular, the size of the structure looks as if the flexible element of the array were excluded, except that it may have more, which means that it means scrolling to the end than omission.

sys/cdefs.h I say:

 #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 way to use it is just [] .

+9
source

Source: https://habr.com/ru/post/989140/


All Articles