ç发现静态数组的大小(preventing错误) [英] C find static array size (preventing mistakes)
问题描述
查找一个静态数组的大小是一种常见的操作。请参阅:Ç发现静态数组大小 - 的sizeof(A)/ sizeof的((一)[0])
Finding the size of a static array is a common operation. see: C find static array size - sizeof(a) / sizeof((a)[0])
这可以被包裹成一个宏,例如:
This can be wrapped into a macro, eg:
的#define ARRAY_SIZE(一)(的sizeof(A)/ sizeof的((一)[0]))
但它可能意外地传递一个普通的指针。
however its possible to accidentally pass in a regular pointer.
例如:无效FUNC(**的someArray富){INT I = ARRAY_SIZE(富); }
虽然它的有效的C,但往往最终成为一个逻辑上的错误。
While its valid C, but often ends up being a logical error.
它可能prevent这个错误的(以每个处理器上零长度位字段失败优势)的
Its possible to prevent this mistake (taking advantage of per-processor to fail on a zero length bit-field).
#define ARRAY_SIZE(a) \
((sizeof(struct { int isnt_array : \
((const void *)&(a) == &(a)[0]); }) * 0) + \
(sizeof(a) / sizeof(*(a))))
我发现与海湾合作委员会这个宏的作品,但失败,铛,对于间接引用的成员。与错误:EX pression是不是一个整数常量前pression
例如:
-
字符字[8]; INT I = ARRAY_SIZE(字);
确定 -
结构酒吧{字[8]; }
结果无效FUNC(结构酒吧*富){INT I = ARRAY_SIZE(foo->的字); }
失败。
char word[8]; int i = ARRAY_SIZE(word);
ok.struct Bar { word[8]; }
void func(struct Bar *foo) { int i = ARRAY_SIZE(foo->word); }
fails.
有没有办法实现这个一个更便携的方式?的(铿锵的工作还是不错的,当然,虽然林兴趣一般便携...其他的编译器也是如此)。的
Is there a more portable way to to implement this? (working with Clang is good of course though Im interested in general portability... other compilers too).
这似乎是这样一个共同的任务,这将是最好有一个可重复使用的便携宏。
This seems such a common task that it would be good to have a re-usable portable macro.
推荐答案
试试这个:
#define ASSERT_ARRAY(a) \
sizeof(char[1-2*__builtin_types_compatible_p(__typeof__(a), __typeof__(&(a)[0]))])
#define ARRAY_SIZE(a) \
(ASSERT_ARRAY(a)*0 + sizeof(a)/sizeof((a)[0]))
这是不可移植的,但兼具 gcc的工作原理
和铛
并有副作用较纳米的少提案。
It is not portable, but works with both gcc
and clang
and has fewer side effects than n.m.'s proposal.
这篇关于ç发现静态数组的大小(preventing错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!