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

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

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.

回答1:

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 [].



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!